0

所以当我的程序启动时,它会尝试从文件中读取产品列表。但如果该文件不存在,则会显示错误并继续。我遇到的问题是当它显示错误时,它不会继续执行 do while 循环

ifstream input;
    input.open("data.txt");


    if (input.fail())
    {
        cout << "\n Data file not found \n";
    }
    ListItemType data; 

    input >> data.productname;
    while(( !input.eof()))
    {
        input >> data.category;
        input >> data.productprice;
        addproduct(head, data); 
        input >> data.productname;
    }

    input.close();
4

1 回答 1

1

它的功能并不相同,但通常最好转向以下内容:

if (std::ifstream input("data.txt"))
{
    ListItemType data; 
    while (input >> data.productname >> data.category >> data.productprice >> data.productname)
        addproduct(head, data);
    if (!input.eof())
        std::cerr << "Error parsing input file.\n";
}    
else
    cout << "\n Data file not found \n";

如果您像上面那样构建 if/else 子句,无论发生什么,它都会按照您的意愿继续执行以下代码。

请注意,上面的代码会在每次输入操作后检查问题。即使读取 data.category 失败,您的代码也会尝试读取 data.productprice。你读 productname 两次有点奇怪,我假设你可以在 I/O 之后调用 addproduct - 如果不是,你需要一个 while 循环,如:

    while (input >> data.productname >> data.category >> data.productprice)
    {
        addproduct(head, data);
        if (!(input >> data.productname))
            break;
    }
于 2013-04-18T02:45:49.783 回答