【问题标题】:Ending an input stream with a specified character, such as '|'?以指定字符结束输入流,例如“|”?
【发布时间】:2020-12-10 03:45:41
【问题描述】:

目前正在学习C++,新手。

我在以“|”结束输入时遇到问题字符,我的程序跳到结尾/结尾并且不允许进一步输入。我相信这是因为 std::cin 由于在期望 int 时输入了字符而处于错误状态,所以我尝试使用 std::cin.clear() 和 std::cin.ignore() 来清除问题并允许程序的其余部分运行,但我似乎仍然无法破解它,任何建议表示赞赏。

int main()
{
    std::vector<int> numbers{};
    int input{};
    char endWith{ '|' };

    std::cout << "please enter some integers and press " << endWith << " to stop!\n";
    while (std::cin >> input)
    {
        if (std::cin >> input)
        {
            numbers.push_back(input);
        }
        else
        {
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max());
        }
    }

然后将向量传递给函数以迭代 x 次并将每个元素添加到总数中,但程序总是跳过用户输入:

std::cout << "Enter the amount of integers you want to sum!\n";
    int x{};
    int total{};
    std::cin >> x;


    for (int i{ 0 }; i < x; ++i)
    {
        total += print[i];
    }

    std::cout << "The total of the first " << x << " numbers is " << total;

请帮忙!

【问题讨论】:

标签: c++ input iostream


【解决方案1】:

当使用输入“|”时(或任何不是int),循环结束并且循环内的错误处理不会执行。只需将错误代码移到循环外即可。此外,您从 stdin 读取了两次,这将跳过每隔一个 int。

while (std::cin >> input) {
    numbers.push_back(input);
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

注意:如果要专门检查“|”可以改成这样:

while (true) {
    if (std::cin >> input) {
        numbers.push_back(input);
    }
    else {
        // Clear error state
        std::cin.clear();
        char c;
        // Read single char
        std::cin >> c;
        if (c == '|') break;
        // else what to do if it is not an int or "|"??
    }
}
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

【讨论】:

    猜你喜欢
    • 2014-01-06
    • 2012-12-11
    • 2016-12-23
    • 1970-01-01
    • 2021-09-20
    • 2011-11-03
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    相关资源
    最近更新 更多