0

while loop in ifstream does not stop even if the the condition is to stop at the end of file also i intended to read the string till it reach either full stop or max 75 character limit for a line then print rest on next line but after printing first line correctly it doesnt read anything

#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;

int main()
{   
    system("cls");
    
    char para[]="The default behaviour of ifstream type stream (upon opening files) allows user to read contents from the file. if the file mode is ios::in only then reading is performed on a text file and if the file mode also includes ios::binary along with ios::in then, reading is performed in binary mode. No transformation of characters takes place in binary mode whereas specific transformations take place in text mode. ";
   puts(para);
    char line[75];
    int a=strlen(para);
    cout<<endl<<"Size of paragraph: "<<a<<endl;
  
    ofstream fout;
    fout.open("out.txt");
    fout.write(para,a);
        fout.close();

    ifstream fin;
    fin.open("out.txt");
    int b=0;
    //char q;
    cout<<endl;
//this loop has the problem
    while (!fin.eof())
    {    
        b++;
        fin.getline(line,74,'.');
        //  if(fin.eof())
        //     break;
     
        cout<<b<<" : "<<line<<"\n";
       
    }
    fin.close();

    return 0;
}
  • You need to change `while (!fin.eof()) { ... fin.getline(line,74,'.'); ... }` to `while (fin.getline(line,74,'.')) { ... }` – Remy Lebeau May 17 '22 at 18:07
  • Don't cross the streams. If you want to use C language I/O (i.e. `puts`) then stick with all the C I/O. If you are going to use C++ I/O (i.e. `getline`), then use all C++ I/O. Don't mix them. For example, instead of `puts(para)`, you could use `std::cout.write(para, sizeof(para));`. – Thomas Matthews May 17 '22 at 20:20
  • can u explain the logic behind while(fin.getline(line,74,'.')) also its not working its not even entering the loop – sujal sharma May 18 '22 at 20:01

0 Answers0