#include <iostream>
    using namespace std;
    using std::cerr;
    using std::cout;
    using std::endl;
    #include <sstream>
 #include <string>

    #include <fstream>
    using std::ifstream;

    #include <cstdlib>


    int main()
    {
       ifstream indata; // indata is like cin
       char num;
       int sar,ri,sat,ha;
       sar=0;ri=0;sat=0;ha=0;
       char s[]=".txt";
     
       for(int some_int=1;some_int<=3;some_int++){
            
       ostringstream buffer;
       buffer <<some_int;
       string s1 =buffer.str();
       
       
       s1+=s; 

      indata.open(s1.c_str());
      if(!indata) { // file couldn't be opened
      cerr << "Error: file could not be opened" << endl;
      cin.get();
      exit(1);
   }
 // opens the file
      
      indata >> num;
       while ( !indata.eof() ) { // keep reading until end-of-file
          switch(num){
                      case 'a':sar+=1;break;
                      case 'b':ri+=1;break;
                      case 'c':sat+=1;break;
                      case 'd':ha+=1;break;}
                      indata >> num;
                       
          }}
       indata.close();
       cout<<"saransh :"<<sar<<"\n"<<"rishul :"<<ri<<"\n"<<"satpal :"<<sat<<"\n"<<"Harsh :"<<ha;
       cout << "\nEnd-of-file reached.." << endl;
       cin.get();
       return 0;
    }

i have 3 files in my src folder named as(1.txt,2.txt and 3.txt) but after using for loop its giving error means its not opening any file......plz help what changes to do so that i can accees these files and their content one by one.

Recommended Answers

All 4 Replies

line 51: close() does not clear the end-of-file flag. After calling close() call clear() so that indata can be used for subsequent loop iterations. Another way to do it is to move line 18 down so that its inside the loop (line 25).

i am not getting you sir, can you write it plzzz

Its only one line of code: infile.clear();

thanks i got it thanks alot..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.