Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

fstream - C++ ofstream not writing to output file?

The code is supposed to count the number of a, b, c, d, e, and f characters in the input text file and print the output into a second text file. When I run the code, it creates the output file but doesn't write anything into it.

#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<<"
Number of b/B characters: "<<bcount;
    oFile<<"
Number of c/C characters: "<<ccount;
    oFile<<"
Number of d/D characters: "<<dcount;
    oFile<<"
Number of e/E characters: "<<ecount;
    oFile<<"
Number of f/F characters: "<<fcount;


//close files
 iFile.close();
 oFile.close();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You've got an endless loop; you do nothing in the loop which would change the state of ifile.eof(). And of course, the condition is wrong to begin with—you never want to use ios_base::eof() as the condition in a loop. Your loop should probably be:

while ( iFile >> x ) {

, although for reading single characters, it might be simpler to use get.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...