【发布时间】:2017-02-14 14:04:11
【问题描述】:
所以在这里我得到了计算文件中字符和单词行数的代码。现在我需要为多个文件实现相同的东西。基本上我的代码应该读取每个文件中 chars 单词和行的数量,并且应该生成 chars 单词和行的总数(将每个文件中的 chars 单词和行的计数相加。我还需要帮助执行代码格式不正确的参数,找不到文件,并且参数无法识别。这是我的代码,我尝试编译它,但它只能读取每个文件中的字符数和字符数,而不是总数。谢谢你们。任何帮助都会非常感谢或建议。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main(int argc, char*argv[])
{
if (argc<2){
cout<<"You did not enter enough arguments, Please try again, close this cd window and enter the correct filename"<<endl;
}
else{
string filename;
ifstream thefile;
int i;
for(i=1,i<=argc;(i++);){
filename=argv[i];
int charactercounter=0, linecounter=1, wordcounter=1, totalLines, totalWords,totalCharacters;
thefile.open(filename);
if(!thefile.is_open()){
cout<<"file does not exist"<<endl;
}
else if(thefile.fail()){
cout<<"arguments can't be recognized"<<endl;
}
if(thefile.is_open() && thefile.good()){
while(!thefile.eof()){
char ch;
while(ch!=EOF){
charactercounter++;
totalCharacters=totalCharacters+charactercounter;
if (ch=='\n')
linecounter++;
totalLines=totalLines+linecounter;
if (ch==' ')
wordcounter++;
totalWords=totalWords+wordcounter;
ch=thefile.get();
}
}
cout<<setw(12)<<"Lines"<<' '<< linecounter;
cout<<' ';
cout<<setw(12)<<"words"<<' '<< wordcounter;
cout<<' ';
cout<<setw(12)<<"characters"<<' '<< charactercounter;
cout<<' ';
cout<<setw(12)<<"filename"<<' '<<argv[i];
cout<<' ';
cout<<setw(12)<<"totallines"<<' '<<totalLines;
cout<<' ';
cout<<setw(12)<<"totalwords"<<' '<<totalWords;
cout<<' ';
cout<<setw(12)<<"totalchars"<<' '<<totalCharacters;
cout<<' ';
thefile.close();
}
}
}
}
【问题讨论】:
-
欢迎来到 Stack Overflow。请花时间阅读The Tour 并参考Help Center 中的材料,您可以在这里问什么以及如何问。
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行逐行检查您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
这段代码对人类来说不容易阅读,这使得寻找错误变得更加困难。应该为程序的不同部分使用函数/类。这样,您可以编写单元测试来检查哪个函数/类的行为不符合预期,而不是多次搜索整个程序来查找每个错误。在编写程序和编写单元测试之前设计一个好的软件架构可能会有所帮助。
标签: c++ command-line-arguments