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

后端 未结 7 1851
故里飘歌
故里飘歌 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

    bool isIntegerNumber(const std::string& string){
      std::string::const_iterator it = string.begin();
      int minSize = 0;
      if(string.size()>0 && (string[0] == '-' || string[0] == '+')){
        it++;
        minSize++;
      }
      while (it != string.end() && std::isdigit(*it)) ++it;
      return string.size()>minSize && it == string.end();
    }
    

提交回复
热议问题