c++ - Reading from text file or stdin -


i have program reads text file , counts number of occurrences of each word on each line. works when reading text file using ifstream, however, if file name not entered on command line, need read stdin instead.

i use following open , read in file currently:

map<string, map<int,int>,compare> tokens; ifstream text; string line; int count = 1;  if (argc > 1){     try{         text.open(argv[1]);     }     catch (runtime_error& x){         cerr << x.what() << '\n';     }      // read file 1 line @ time, replacing non-desired char's spaces     while (getline(text, line)){         replace_if(line.begin(), line.end(), my_predicate, ' ');          istringstream iss(line);             // parse line on white space, storing values tokens map         while (iss >> line){                             ++tokens[line][count];         }         ++count;     } }  else{ while (cin) {     getline(cin, line);     replace_if(line.begin(), line.end(), my_predicate, ' ');      istringstream iss(line);     // parse line on white space, storing values tokens map     while (iss >> line){         ++tokens[line][count];     }     ++count; } 

is there way assign cin ifstream , add else statement if argc > 1 fails, using same code afterwards instead of duplicating this? haven't been able find way this.

make reading part function of own. pass either ifstream or cin it.

void readdata(std::istream& in) {    // necessary work read data. }  int main(int argc, char** argv) {    if ( argc > 1 )    {       // input file has been passed in command line.       // read data it.       std::ifstream ifile(argv[1);       if ( ifile )       {          readdata(ifile);       }       else       {          // deal error condition       }    }    else    {       // no input file has been passed in command line.       // read data stdin (std::cin).       readdata(std::cin);    }     // needful process data. } 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -