How to read from input file (text file) and validate input as valid integer?

前端 未结 2 378
执念已碎
执念已碎 2020-12-22 08:06

I\'m writing a program which needs to read a text file and check first line of the text file for a number between 0 to 10. I have come up with a couple of solutions but ther

2条回答
  •  不思量自难忘°
    2020-12-22 08:52

    #include 
    #include 
    #include 
    #include 
    using namespace std;
    
    bool isValidNumber (string str)
    {
      if (str.length() > 2 || str.length() == 0)
        return false;
      else if (str.length() == 2 && str != "10")
        return false;
      else if (str.length() == 1 && (str[0] < '0' || str[0] > '9'))
        return false;
      return true;
    }
    
    int main()
    {
      ifstream fin(argv[1]);
      if(!fin.good())
      {
        cout<<"File does not exist ->> No File for reading";
        exit(1);
      }
    
      //To check file is empty http://stackoverflow.com/a/2390938/1903116
      if(fin.peek() == std::ifstream::traits_type::eof())
      {
        cout<<"file is empty"<

提交回复
热议问题