The one that always occurs when you enter a character where the program is expecting an integer?
This is in a command line application using Standard C++ (not visual or anything like that).
The one that always occurs when you enter a character where the program is expecting an integer?
This is in a command line application using Standard C++ (not visual or anything like that).
why dont you change the int to a char?
Because I need to perform mathematical operations using user inputs...
you can store the user input into a char first, and use isdigit() function to check if it is an integer, if the isdigit() returns true,then convert the char into an integer.it is simple
blow me ... ...
You need to always check the status of the stream and loop on .good(), never .eof()
another example reading a number of ints into a vector in {2, 3,5} formatCode:while(cin) { int x; while(!(cin >> x)) { cin.clear(); std::string token; if(cin >> token && token != "quit") { cout << "expected integer, read \"" << token << '"' << endl; } else { cerr << "unrecoverable stream error while expecting integer" << endl; /****throw abort return or whatever, bail out here****/ } } /*** x is valid here ***/ }
Code:bool readvec(std::vector<int> &v, std::istream &is=std::cin) { char ch; if(is >> ch && ch == '{') { int n; while(is >> n >> ch && ch == ',') v.push_back(n); if(ch == '}') { v.push_back(n); return true; } } return false; }
Data validation can be done reading everything into a string first, then validating the input, then converting to appropriated data type (int, float have built in data conversion functions). Alternatively, you can monitor stream methods (for example good(), fail(), clear(), ignore()) for appropriate input. Both approaches have their advantages and disadvantages. I'd suggest a board search as this topic comes up reasonably often.