C++ Fix for checking if input is an integer
c++, integer
Solution
Two possible solutions:
- First store the input in a std::string instead of directly to an int. Then, use strtol from for converting to an integer. If the endPtr points to 0, it means nothing is left at the end, so this is OK. Otherwise, some no number characters are found at the end
- In your example, `std::cin >> dblMarkOne;` will leave non-number characters in `std::cin`, so if there is still data available in `std::cin` after, for instance by using `std::cin.peek()!=EOF`, this means the user has entered more than a number.
Edit : full tested code:
#include <iostream>
#include <cstdio>
int main(int argc, char ** argv)
{
bool ok = false;
int dblMarkOne;
std::cout << "Enter a number" << std::endl;
while (!ok)
{
std::cin >> dblMarkOne;
if(!std::cin.fail() && (std::cin.peek()==EOF || std::cin.peek()=='\n'))
{
ok = true;
}
else
{
std::cin.clear();
std::cin.ignore(256,'\n');
std::cout << "Error, Enter a number" << std::endl;
}
}
}
Problem
for example, if I enter "2a", it does not show an error nor asks the user to re-input the value. how do i fix this? ``` while (std::cin.fail()) { std::cout << "ERROR, enter a number" << std::endl; std::cin.clear(); std::cin.ignore(256,'\n'); std::cin >> dblMarkOne; } std::cout << "" << std::endl; ```