Question

In case of an invalid input, I want extract the invalid input from cin and store it in a variable that fits. How can I do that?

#include<iostream>

using namespace std;

int main(){
    int number;
    cout << "Enter a number: " << endl;
    cin >> number;

    if(cin.fail()){
    cout << "Error!" << endl;
    //HOW CAN I STORE THE INVALID INPUT WHICH IS STORED IN cin INTO A STRING?
    }   

return 0;

}

Was it helpful?

Solution

When you detect that failbit is set, reset it, and use std::getline to read entire line of invalid input into std::string from std::cin:

#include <iostream>
#include <string>


int main()
{
        int number;

        while(true)
        {
                std::cout << "Enter a number (0 to exit): " << std::endl;
                std::cin >> number;

                if(std::cin.fail())
                {
                        std::string error_data;
                        std::cin.clear(std::cin.rdstate() & ~std::ios::failbit);
                        std::getline(std::cin, error_data);
                        std::cout << "You didn't enter a number - you've entered: " << error_data << std::endl;

                }
                else
                {
                        std::cout << "Number is: " << number << std::endl;
                        if(number == 0)
                        {
                                break;
                        }
                }

        }
        return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top