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

前端 未结 2 379
执念已碎
执念已碎 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:50

    I would probably read the line with std::getline, then use a Boost lexical_cast to convert to int. It will throw an exception unless the entirety of the input string can be converted to the target type -- exactly what you want.

    Of course, you'll also need to check that the converted result is in the correct range, and also throw the exception if it's out of range.

    0 讨论(0)
  • 2020-12-22 08:52
    #include <iostream>
    #include <fstream>
    #include <cstdio>
    #include <cstdlib>
    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"<<endl;
        exit(1);
      }
      string tmp;
      getline(fin,tmp);
      if (isValidNumber(tmp) == false)
      {
        cerr << "Invalid number : " + tmp << endl;
      }
      else
      {
        cout << "Valid Number : " + tmp << endl;
      }
    }
    
    0 讨论(0)
提交回复
热议问题