Search code examples
c++inputiostream

Ending an input stream with a specified character, such as '|'?


Currently learning C++, newbie.

I have an issue when ending the input with the '|' character, my program skips to the end/ends and does not allow for further input. I believe it is because std::cin is in an error state due to inputting a char when expecting an int, so i have tried to use std::cin.clear() and std::cin.ignore() to clear the issue and allow the remainder of the programme to run but I still cannot seem to crack it, any advice appreciated.

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());
        }
    }

And then pass the vector to a function to iterate through x amount of times and add each element to a total, but the program always skips past the user input:

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;

Please help!


Solution

  • When the use enters a "|" (or anything that is not an int), the loop ends and the error handling that is inside the loop does not execute. Just move the error code to outside the loop. Also, you read from stdin twice which will skip every other int.

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

    Note: If you want to specifically check for "|" can change to something like this:

    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');