读取文件的 C++ 程序

c++ program reading a file

本文关键字:程序 C++ 文件 读取      更新时间:2023-10-16

我的代码:

void load_books(){
ifstream myfile(path, ios::in);
if (myfile.fail()){
    cout << "coudln't open file" << "nn";
}
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();
}
}

它应该输出文件包含的内容,但我在命令中得到这个

111 艾哈迈德·优素福 哈哈 不 是 哈立德 15

222 ADAS ASD SDT huy mjmj mjg2 20

0

0

前两行是正确的,但我不知道为什么它输出最后 2 个零 (0 0)

充实@Bo的答案,并回答您的评论:

以及我如何在每次尝试输入后检查 myfile 的状态??!

您可以像这样修复循环:

void load_books(){
    ifstream myfile(path);
    if (myfile.fail()){
        cout << "coudln't open file" << "nn";
    }
    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++;   
        }
    }
}

由于std:istream& operator>>(std:istream&, T&)的链式调用返回当前std:istream&引用,因此while()循环中的条件可以解析为std::basic_ios::operator bool,并且一旦运算符计算到false,循环就会结束。

相关参考文档:

  • operator>>(std::basic_istream)
  • std::basic_ios::operator bool

条件 while(myfile) 仅在某些输入失败停止。

此时,您已经打印了该输入尝试的零。

您必须在每次尝试输入后检查myfile的状态,以查看它是否成功。