How to determine if a string is a number with C++?

后端 未结 30 2511
遇见更好的自我
遇见更好的自我 2020-11-22 08:46

I\'ve had quite a bit of trouble trying to write a function that checks if a string is a number. For a game I am writing I just need to check if a line from the file I am r

30条回答
  •  佛祖请我去吃肉
    2020-11-22 09:09

    With this solution you can check everything from negative to positive numbers and even float numbers. When you change the type of num to integer you will get an error if the string contains a point.

    #include
    #include
    using namespace std;
    
    
    int main()
    {
          string s;
    
          cin >> s;
    
          stringstream ss;
          ss << s;
    
          float num = 0;
    
          ss >> num;
    
          if(ss.good()) {
              cerr << "No Valid Number" << endl;
          }
          else if(num == 0 && s[0] != '0') {
              cerr << "No Valid Number" << endl;
          }
          else {
              cout << num<< endl;
          }             
    }
    

    Prove: C++ Program

提交回复
热议问题