samedi 1 juillet 2017

eof() for file containing string and integer datatypes .c++

 #include<iostream>
#include<fstream>
using namespace std;
int main(){
    string name="Stephen Hawks";
    int age=75;
    //saves info in file
    ofstream file;
    file.open("serial.txt",ios::out|ios::app|ios::in);
    file<<name<<endl;
    file<<age<<endl;
    file.close();
   //--------------------
    name=" ";
    age=0;
    //restore info from file
    ifstream file2;
    file2.open("serial.txt",ios::in);
    while(!file2.eof()){
      getline(file2,name);
      cout<<name<<endl;
      file2>>age;
     cout<<age<<endl;
    }   
}

Hi. This code gives infinite empty name and 0 integer output. there are multiple questions about eof() function in here but i still cant figure it out. please help. if i use condition while(file2>>name) then i cant initialize data in variables name and age which i need.

Aucun commentaire:

Enregistrer un commentaire