-1

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<<"\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();
}
John Dibling
  • 99,718
  • 31
  • 186
  • 324
Cara McCormack
  • 388
  • 1
  • 7
  • 21

2 Answers2

5

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.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
3

Insert the following line inside at the while statement(at the end of it):

iFile>>x;

Before, you scanned only the first value of x, so the while loop continued for ever.

Rontogiannis Aristofanis
  • 8,883
  • 8
  • 41
  • 58
  • That will prevent the endless loop, but it still isn't correct. – James Kanze Oct 15 '12 at 18:42
  • The loop condition is wrong, see James's answer, and [this](http://stackoverflow.com/questions/21647/reading-from-text-file-until-eof-repeats-last-line) and [this](http://www.parashift.com/c++-faq-lite/istream-and-eof.html) – jrok Oct 15 '12 at 18:48
  • the loop is still using `eof()` as its termination condition. – James Kanze Oct 16 '12 at 07:17