从文件循环输入流



我试图让我的程序遍历文件,每次都接收大量信息。但是,在正确输入 2 行后的那一刻,无论文件的内容如何,它始终变为默认值。最初它是一个 eof while 循环,但我将其更改为 for 循环以尝试修复它。这是我的代码:

ifstream furniture;
furniture.open("h://furniture.txt");

for(int i=0;i<=count;i++)
{
    type=0;
    furniture>>type>>name>>number>>material>>colour>>mattress;
    switch (type)
    {
    case 1:
        {
            Item* item= new Bed(number, name, material, colour, mattress);
            cout<<"working, new bed"<<endl;
            v.push_back(item);
            cout<<"working pushback"<<endl;
            count++;
            break;
        }
    case 2:
        {
            Item* item= new Sofa(number, name, material, colour);
            cout<<"working, new sofa"<<endl;
            v.push_back (item);
            cout<<"working pushback"<<endl;
            count++;
            break;
        }
    case 3:
        {
            Item* item= new Table(number, name, material, colour);
            cout<<"working, new table"<<endl;
            v.push_back(item);
            cout<<"working pushback"<<endl;
            count++;
            break;
        }
    default:
        {
            cout<<"Invalid input"<<endl;
            type=0;
            break;
        }
    }
}

我已经尝试了一系列不同的解决方案,但似乎没有什么能解决问题。任何帮助将不胜感激。

如果

读取失败,ifstreamoperator>>不会更改变量,因此type保持为 0,因此调用默认分支。 您的文件似乎存在格式错误,导致读取失败。

根据您的评论,您可能并不总是在文件中拥有所有值,您可以执行以下操作:

最好的方法是使用 getline() 读取整行,然后使用 stringstream 从行中提取值,处理过程中的可选值:

string line;
getline(furniture, line);
stringstream ss(line);
ss>>type>>name>>number>>material>>colour>>mattress;

如果为所有这些变量提供默认值,则当行格式不正确或不包含所有变量时,它们将保留默认值。

在这里使用 getline() 的优点是,如果当前行出现问题,通过 op>> 提取不会弄乱后续行。

最新更新