查找文件中最长的单词

时间:2017-10-02 19:48:38

标签: c++ file text get getline

大家好我正在尝试编写一个程序,找到文件中最长的行和单词ifstream。我有程序找到最长的线,但我找到最长的单词有困难。这就是我现在所拥有的。

这是我得到的错误。

#include <iostream>
#include<stdlib.h>
#include<getopt.h>
#include"stdio.h"
#include<fstream>
//#include<sstream>

using namespace std;

int main(int argc, char *argv[]) {

   size_t longest = 0;
   string longestWord;
   int Lcount = 0;
   int Wcount = 0;
   int option;
   string line;
   string word;

    if(argc <= 1)
    {
       cout << "NO FILES\n";
       return 0;
    }
   else
   {

   for(int i = 1;i<argc;i++){
      ifstream file (argv[i]);
      if (!file.is_open() ){
      cout << argv[i] << " FILE NOT FOUND\n"; // watch out for /n
      }
     //else if(!file.close()){
        // cout << argv[i] << "NO FILES\n"; }
      else{
         while (getline(file,line))// Length of Longest Line
         {
            if(line.size() > longest){
               longest = line.size(); 
         }
            else if(line.size() == longest){// Number of lines with longest length
                     ++Lcount;}
         }
         while (get(file,word))
         {
            if(word.size() > longestWord.size()){
               longestWord = word; 
         }
            else if(word.size() == longestWord.size()){
                     ++Wcount;}
         }

   }
   }
   }

     while ((option = getopt (argc, argv, "c:")) != -1){
        switch (option)
        {
           case 'c': 
              {
              for(int i = 1;i<argc;i++){
                  ifstream file (argv[i]);

              cout << argv[i] << "\n";
              cout << longestWord << " (" << Wcount << ")" << "\n";
              cout << longest << " (" << Lcount << ")" << "\n";
                 break;
              }
              }

                 default: 
                 //cout << "UNRECOGNIZED FLAG\n";
              if(option != 'c'){
                 cout << "UNRECOGNIZED FLAG\n";
                 return 0;}

        }
     }

        //if (option != 'c')
           //cout << "UNRECOGNIZED FLAG\n";

   return 0;
}

据我所知,getline用于获取实际行,而get应该获取该行中的字符。

{{1}}

1 个答案:

答案 0 :(得分:1)

您所包含的库中没有与您的get函数等效的内容。尝试使用文件&gt;&gt; word而不是get。同样ifstream再次使用不同的变量来获得单词。请参阅http://www.cplusplus.com/forum/general/34420/以供参考。