How to check if the input is a valid integer without any other chars?

后端 未结 7 1965
故里飘歌
故里飘歌 2020-11-28 15:36
#include 
#include 

using namespace std;

int main()
{
    int x;
    cout << \"5 + 4 = \";
    while(!(cin >> x)){
               


        
7条回答
  •  悲哀的现实
    2020-11-28 16:06

    You could read a string, extract an integer from it and then make sure there's nothing left:

    std::string line;
    std::cin >> line;
    std::istringstream s(line);
    int x;
    if (!(s >> x)) {
      // Error, not a number
    }
    char c;
    if (s >> c) {
      // Error, there was something past the number
    }
    

提交回复
热议问题