c++ - How to read from input file (text file) and validate input as valid integer? -
i'm writing program needs read text file , check first line of text file number between 0 10. have come couple of solutions there still problem:
how read file:
const string filename= argv[1]; ifstream fin(argv[1]); if(!fin.good()){ cout<<"file not exist ->> no file reading"; exit(1); } getline(fin,tmp); if(fin.eof()){ cout<<"file empty"<<endl; } stringstream ss(tmp);
first used atoi:
const int filenum = atoi(tmp.c_str()); if(filenum<1 || filenum>10){ cout<<"number of files incorrect"<<endl; //exit(1); }
if first line character, change 0 want call exception , terminate program.
then used isdigit
entry string , not work string. used each character in string still not work.
stringstream ss(tmp); int i; ss>>i; if(isdigit(tmp[0])||isdigit(tmp[1])||tmp.length()<3) {}
#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 not exist ->> no file reading"; exit(1); } //to check file empty http://stackoverflow.com/a/2390938/1903116 if(fin.peek() == std::ifstream::traits_type::eof()) { cout<<"file empty"<<endl; exit(1); } string tmp; getline(fin,tmp); if (isvalidnumber(tmp) == false) { cerr << "invalid number : " + tmp << endl; } else { cout << "valid number : " + tmp << endl; } }
Comments
Post a Comment