Hi, how do you check if a number inputted by cin object is a integer? If it's a double then i want it to spit out an error and ask me to input another number.
I'm not very good a terminology yet, I'm still learning. I was actually thinking you could use a function like substr() or something and check for either of those characters... maybe it was a bad suggestion >.<
Hi, I'm also a newbie but I think this should work:
1 2 3 4 5 6
int test;
while (!(cin >> test))
{
cout << "Wrong input. Please, try again: ";
cin.clear();
}
If there's a double (. character) or a string in the input queue the cin object should be false (0), so if you put !, it keeps asking you for the right input.
#include <ctype.h>
bool TFmBatteryConfiguration::IsValidInt(char* x)
{
bool Checked = true;
int i = 0;
do
{
//valid digit?
if (isdigit(x[i]))
{
//to the next character
i++;
Checked = true;
}
else
{
//to the next character
i++;
Checked = false;
break;
}
} while (x[i] != '\0');
return Checked;
}
What you do basically is that check every single character in the input looking for any "invalid digit".
@ResidentBiscuit
Yes, but the problem is that the number before the dot in the double input is an integer so it doesn't fail. The dot and everything after it is left in the stream.
I guess you could solve it by first reading the integer number as usual. Then read the rest of the line with std::getline and check that it only contains white space.
double getNum(void)
{
double num;
while (!(cin >> num))
{
cin.clear();
cin.ignore(80, '\n');
cout << "Sorry, not a number: ";
}
cin.ignore(80, '\n');
return num;
}
// Which makes getInt() like this:
int getInt(void)
{
double num = getNum();
while (// not an integer...
return num;
}
#include <iostream>
#include <sstream>
int get_int(char *message)
{
usingnamespace std;
int out;
string in;
while(true) {
cout << message;
getline(cin,in);
stringstream ss(in); //covert input to a stream for conversion to int
if(ss >> out && !(ss >> in)) return out;
//(ss >> out) checks for valid conversion to integer
//!(ss >> in) checks for unconverted input and rejects it
cin.clear(); //in case of a cin error, like eof() -- prevent infinite loop
cerr << "\nInvalid input. Please try again.\n"; //if you get here, it's an error
}
}
int main()
{
int i = get_int("Please enter an integer: ");
}