ここでは、ファイル内の行と文字の数を数えるコードを得ました。次に、複数のファイルに対して同じことを実装する必要があります。基本的に私のコードは、各ファイルのchars単語と行の数を読み取る必要があります(chars単語と行の数を各ファイルから追加するchars単語と行の合計を生成する必要があります。私はまた、 、ファイルが見つからない、認識できない引数があります。これは私のコードですが、コンパイルしようとしましたが、各ファイルのcharsの単語と文字数を読み込み、total.Thankを追加しませんでした。大幅理解や提案する。2つのファイルの文字と行の総数を数えて合計して合計を計算するにはどうすればよいですか?
#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();
}
}
}
}
ようこそスタックオーバーフロー。 [The Tour](http://stackoverflow.com/tour)を読み、[ヘルプセンター](http://stackoverflow.com/help/asking)の資料を参考にしてください。ここに聞いてください。 –
このような問題を解決する適切なツールは、デバッガです。スタックオーバーフローを尋ねる前に、コードを一行ずつ進める必要があります。詳しいヘルプは、[小さなプログラムをデバッグする方法(Eric Lippert)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)を参照してください。最低限、問題を再現する[最小、完全、および検証可能](http://stackoverflow.com/help/mcve)の例と、その問題を再現するためのデバッガ。 –
このコードは人間が読むのが容易ではなく、バグを探しにくくなります。プログラムのさまざまな部分に関数/クラスを使用する必要があります。そうすれば、プログラム全体を何度も検索して各バグを探す代わりに、どの関数/クラスが期待どおりに動作していないかを確認するための単体テストを書くことができます。プログラムを書いて単体テストを書く前に良いソフトウェアアーキテクチャを設計することは役に立ちます。 –