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
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.
#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;
}
}