【问题标题】:Loop for instream from file从文件循环输入流
【发布时间】:2012-05-10 22:47:01
【问题描述】:

我正试图让我的程序循环遍历文件,每次都接收大量信息。但是,在正确输入 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;
        }
    }
}

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

【问题讨论】:

  • 文件中有什么?它是正确处理前两行还是第二行已经不同步?变量typenamenumber 等在您的默认情况下意外着陆时是什么?

标签: c++ loops inputstream


【解决方案1】:

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

根据您的评论,您可能不会一直拥有文件中的所有值,您可以这样做:

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

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

如果您为所有这些变量提供默认值,如果行格式错误或不包含所有变量,它们将保持默认值。

这里使用getline()的好处是,如果当前行有问题,通过op&gt;&gt;提取不会弄乱后续行。

【讨论】:

  • 我刚刚意识到这可能是由于文件中并非所有对象都有 matress 值,如果文件中没有,有没有办法设置默认值?
  • 使用 stringstream 需要特定的包含文件吗?
  • @bemusedandconfused, #include &lt;sstream&gt;.
猜你喜欢
  • 2017-04-20
  • 2013-12-12
  • 1970-01-01
  • 2015-03-16
  • 2017-10-12
  • 2016-03-06
  • 2013-06-05
  • 2012-09-27
  • 1970-01-01
相关资源
最近更新 更多