-1

该代码应该计算输入文本文件中 a、b、c、d、e 和 f 字符的数量,并将输出打印到第二个文本文件中。当我运行代码时,它会创建输出文件,但不会向其中写入任何内容。

#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 回答