Is this the correct approach to do input validation with floating point values?

后端 未结 4 1493
忘了有多久
忘了有多久 2021-01-22 11:26

After spending a good amount of time researching input validation, I combined a few ideas and came up with this:

Function to check a string for a valid dou

4条回答
  •  悲&欢浪女
    2021-01-22 12:09

    If it's an exercise you want, that's understandable. But otherwise, you can use istringstream to avoid reinventing the wheel:

    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main () {
    
      int n,val;
      string stringvalues;
    
      stringvalues = "3.14159254 f01fhasfljk";
      istringstream iss(stringvalues);
    
      float x,y;
      iss >> x;
    
      cout << x * 2 << endl;
    
      iss >> y;
      if ( ! iss.fail() )
        {
          cout << y * 2 << endl;
        }
      else
        {
          cout << "second value not a number..." << endl;
        }
    
      return 0;
    }
    

提交回复
热议问题