0

Question: Close the file when an empty string "" is entered. Problem : The program is ending after the first set of input and I tried something before and no action is being taken when entering an empty string

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

int main() {
    string filename, studID ;
    float mark1,mark2,mark3 ;
    
    cout<<"Enter file name: ";
    getline (cin, filename);
    ofstream studfile(filename) ;
    
    if(!studfile) {  //Check if file is open successfully
        cout<<"Student file failed to open !"<<endl ;
    }else{
        cout<<"Student file is open..."<<endl ;
        
        cout<<"Enter student ID: ";
        getline (cin, studID);
        
        while (studID != ""){
            
            cout<<"Enter mark for test one: ";
            cin>>mark1 ;
            cout<<"Enter mark for test two: ";
            cin>>mark2 ;
            cout<<"Enter mark for test three: ";
            cin>>mark3 ;
            
            studfile<<studID<<"\t"<<mark1<<"\t"<<mark2<<"\t"<<mark3<<endl ;
            cout<<"Write done !" <<endl ;
            
            cout<<"Enter student ID: ";
            getline (cin, studID);
            
         }
    }
    
    
    
    studfile.close () ;
    
    
    return 0;
}
  • 2
    Print your inputs directly after reading them, preferrably surrounded with some kind of delimiter (so you you can "see" whitespace). Then read [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction). – molbdnilo Feb 03 '21 at 12:45

0 Answers0