简体   繁体   中英

c++ program reading a file

My code :

void load_books(){
ifstream myfile(path, ios::in);
if (myfile.fail()){
    cout << "coudln't open file" << "\n\n";
}
else{

    while (myfile){
        myfile >> book1[i].id >> book1[i].title >> book1[i].p_name >> book1[i].p_address >> book1[i].aut_name;
        myfile >> book1[i].aut_nationality >> book1[i].date >> book1[i].status;


        cout << book1[i].id << "\ " << book1[i].title << "\ " << book1[i].p_name << "\ " << book1[i].p_address << "\ " << book1[i].aut_name;
        cout << "\ " << book1[i].aut_nationality << "\ " << book1[i].date << "\ " << book1[i].status << endl;
        i++;

    }
    myfile.close();
}

}

it should outputs what file contain but i get this in the command

111 ahmed yousef lol no yes khaled 15

222 adas asd sdt huy mjmj mjg2 20

0 0

the first two lines are correct but I don't know why it outputs the last 2 zeroes (0 0)

The condition while(myfile) will only stop after some input has failed.

At that point you have already printed the zeros from that input attempt.

You have to check the status of myfile after each attempted input, to see if it succeeded.

To flesh out @Bo's answer , and answering your comment :

and how i check the status of myfile after each attempted input??!

You can fix your loop like this:

void load_books(){
    ifstream myfile(path);
    if (myfile.fail()){
        cout << "coudln't open file" << "\n\n";
    }
    else{
         while (myfile >> book1[i].id >> book1[i].title >> book1[i].p_name 
                       >> book1[i].p_address >> book1[i].aut_name 
                       >> book1[i].aut_nationality >> book1[i].date >> book1[i].status){

            cout << book1[i].id << "\ " << book1[i].title << "\ " << book1[i].p_name << "\ " 
                 << book1[i].p_address << "\ " << book1[i].aut_name << "\ " 
                 << book1[i].aut_nationality << "\ " << book1[i].date << "\ " 
                 << book1[i].status << endl;
            i++;   
        }
    }
}

Since the chained calls of std:istream& operator>>(std:istream&, T&) return the current std:istream& reference, the condition in the while() loop can be resolved to the std::basic_ios::operator bool , and the loop will end as soon the operator evaluates to false .

Related reference documentation:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM