2017-02-18 2 views
0

私は複数のファイルがコマンドライン引数として使用されるプログラムを作成しています。たとえば、コマンドプロンプトでprogram.exe file1.txt file2.txtを出力します。何らかの理由で私の出力は正しい結果を示していません。 2つのファイル名を入力すると、最初のファイル名が2回だけ表示されます。スクリーンショットを添付しました。また、文字や文字をカウントしません。私はそれがローカル変数やグローバル変数で何かをしなければならないと考えましたが、私はそれらを全面に置いてみました。あるいは私自身の間違いを知りませんでした。私はアドバイスに感謝します。私のプログラムは、行数や文字の数をカウントしませんか?

#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

答えて

2

多くの問題がここにあります。まず、chを初期化せずに使用しています。次に、最初の文字を読み取った後にファイルストリームをクローズします。 while (ch!= EOF){...}ブロックの後に、統計とファイル名を出力することをお勧めします。適切なインデントは、物事をより明確にするのに役立ちます。

関連する問題