Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - How to determine whether the input data is an integer in C++
How to determine whether the input data is an integer in C++

Define the string string s that receives the content, and call the C++ getline method. The format is as follows: getline(cin, s). getline can receive spaces and ends when it encounters a newline input. Then determine whether the characters in the string are numbers. If a non-number character is encountered, it is not an integer.

bool isDigit(char a) {

if (a - '0' == 0 || a - '0' == 1 || a - '0' == 2 || a - '0' == 3 ||

a - '0' == 4 || a - '0' == 5 || a - '0' == 6 || a - '0' == 7 ||

a - '0' == 8 || a - '0' == 9)

return true;

return false;

}

void testInteger(string y) {

for (int i = 0; i

if (!isDigit(y[i])) {

cout<<"The input content is not an integer... "<

return;

}

//Convert string to number

int num;

isringstream t(y);

t >> num;

cout<<"The integer is:"<

}

int main(){

string s;

cout << "Please enter an integer:"<

getline(cin, s);

testInteger(s);

return 0;

}

Extended information:

p>

C++ method to judge input function:

//is int?bool isDegital(string str) {//Judge the case of no input

if(str==" ")

{

return false;

}

else {//If there is input

for (int i = 0;i < str.size();i++)?

{

if (str.at(i) == '-' && str.size () > 1) ?// Negative numbers may appear

continue;

The value is between '0'-'9' of the ascii code (encoding) if (str.at (i) > '9' || str.at(i) < '0') ?

return false;

}

return true;< /p>

}

}