-1

このコードは、入力テキストファイル内のa、b、c、d、e、およびf文字の数をカウントし、出力を2番目のテキストファイルに出力することになっています。コードを実行すると、出力ファイルが作成されますが、何も書き込まれません。

#include<iostream>
#include<fstream>
#include<cmath>
using namespace std;


int main(){

// establish counters for the number of each character
char x;
int acount=0;
int bcount=0;
int ccount=0;
int dcount=0;
int ecount=0;
int fcount=0;

 ifstream iFile("plato.txt"); //define & open files
 ofstream oFile("statistics.txt");

 if(!iFile){
  cout<<"The file could not be opened.";
  exit(1);
 }

 if(!oFile){
  cout<<"The file could not be opened.";
  exit(1);
 }

 iFile>>x;

 while(!iFile.eof()){
  if(x=='a'||x=='A'){
   acount++;
  }
  else if(x=='b'||x=='B'){
   bcount++;
  }
  else if(x=='c'||x=='C'){
   ccount++;
  }
  else if(x=='d'||x=='D'){
   dcount++;
  }
  else if(x=='d'||x=='D'){
   dcount++;
  }
  else if(x=='f'||x=='F'){
   fcount++;
  }
}



    oFile<<"Number of a/A characters: "<<acount; //write number of characters into statistics file
    oFile<<"\nNumber of b/B characters: "<<bcount;
    oFile<<"\nNumber of c/C characters: "<<ccount;
    oFile<<"\nNumber of d/D characters: "<<dcount;
    oFile<<"\nNumber of e/E characters: "<<ecount;
    oFile<<"\nNumber of f/F characters: "<<fcount;


//close files
 iFile.close();
 oFile.close();
}
4

2 に答える 2

5

無限ループがあります。の状態を変更するループでは何もしませんifile.eof()。そしてもちろん、そもそも条件が間違ってios_base::eof()います。ループ内で条件として使用することは決してありません。ループはおそらく次のようになります。

while ( iFile >> x ) {

、ただし、単一の文字を読み取る場合は、 を使用する方が簡単かもしれませんget

于 2012-10-15T18:41:38.230 に答える
3

次の行を while ステートメントの内側 (最後) に挿入します。

iFile>>x;

以前は、x の最初の値だけをスキャンしていたため、while ループは永遠に続きました。

于 2012-10-15T18:37:25.700 に答える