Reading from text file or stdin

喜夏-厌秋 提交于 2019-12-14 03:47:34

问题


I have a program that basically reads a text file and counts the number of occurrences of each word on each line. Everything works properly when reading from a text file using an ifstream, however, if a file name is not entered on the command line, I need to read from stdin instead.

I use the following to open and read in the 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 one line at a time, replacing non-desired char's with spaces
    while (getline(text, line)){
        replace_if(line.begin(), line.end(), my_predicate, ' ');

        istringstream iss(line);    
        // Parse line on white space, storing values into 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 into tokens map
    while (iss >> line){
        ++tokens[line][count];
    }
    ++count;
}

Is there a way to assign cin to an ifstream and simply add an else statement if argc > 1 fails, using the same code afterwards instead of duplicating like this? I haven't been able to find a way to do this.


回答1:


Make the reading part a function of its own. Pass either an ifstream or cin to it.

void readData(std::istream& in)
{
   // Do the necessary work to read the data.
}

int main(int argc, char** argv)
{
   if ( argc > 1 )
   {
      // The input file has been passed in the command line.
      // Read the data from it.
      std::ifstream ifile(argv[1]);
      if ( ifile )
      {
         readData(ifile);
      }
      else
      {
         // Deal with error condition
      }
   }
   else
   {
      // No input file has been passed in the command line.
      // Read the data from stdin (std::cin).
      readData(std::cin);
   }

   // Do the needful to process the data.
}



回答2:


You cannot assign cin to an ifstream.
But you could reopen cin to some file.

Anyway, the better method would be modularising your code and just using a std::istream&.



来源:https://stackoverflow.com/questions/23050273/reading-from-text-file-or-stdin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!