c++ - 我的程序无法正确计算单词或字符的行数?

标签 c++ file parsing command-line-arguments

所以我正在编写一个程序,其中多个文件采用命令行参数。例如,我在命令提示符下输出 program.exe file1.txt file2.txt。出于某种原因,我的输出没有显示正确的结果。当我输入两个文件名时,它只显示第一个文件名两次。我附上了截图。它也不计算字符单词或字符。我认为它必须对局部或全局变量做一些事情,但我已经尝试将它们放在各处。或者我可能对自己的错误视而不见。我将不胜感激任何建议。

 #include <iostream>
 #include <string>
 #include <iomanip>
 #include  <fstream>

using namespace std;
int i;
char ch;
int charcounter=0;
int wordcounter=0;
int linecounter=0;

int main(int argc, char* argv[])
 {
 for ( i = 1; i < argc; i++ ){

  if (argc<2){
    cout<<"you did not enter enough arguments"<<endl;
  }
    else {
        string filename;
        ifstream thefile;
        filename=argv[i];

        thefile.open(argv[i]);
        if (thefile.is_open() && thefile.good())
        {
                while (ch!= EOF){
                    charcounter++;

                    if (ch ==' ')
                    wordcounter++;
                   else if (ch =='\n')
                        linecounter++;

                ch=thefile.get();
                cout<<setw(12)<<"Lines"<<' '<<linecounter;
                cout<<' ';
                cout<<setw(12)<<"Words"<<' '<<wordcounter;
                cout<<' ';
                cout<<setw(12)<<"Characters"<<' '<<charcounter;
                cout<<' ';
                cout<<"filename"<<' '<<argv[i];
                thefile.close();
            }
        }
    }
}
 }

enter image description here

最佳答案

这里有很多问题。首先,您在未初始化的情况下使用 ch。其次,您在读取第一个字符后关闭文件流。您可能希望在 while (ch!= EOF){...} block 之后打印统计信息和文件名。适当的缩进有助于使事情更清楚。

关于c++ - 我的程序无法正确计算单词或字符的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42311268/

相关文章:

php - HTML Dom 解析 5000 + 项

C++11 lambda函数对象成员

python - 文件太大无法读取

ruby - 如何用 ruby​​ 向后读取文件然后向前读取文件?

c - fprintf() 和 fputs() 没有得到正确的结果

从字节流中解析可变长度描述符并作用于它们的类型

c++ - MSXML4 和设置编码字符串

c++ - 从文件中读取 double

C++ 指针转换

parsing - 真实世界 Haskell 的 CSV 解析器实现