C ++:ostream错误<<操作者

时间:2016-09-08 15:28:17

标签: c++ c++11 iostream

我不明白为什么这段代码会给我错误

void printSalesFile(vector< vector<float> > & list)
{
    ofstream outfile;
    outfile.open("sales.lst", ios::out);
    if (outfile.is_open())
    {
        outfile << setw(6) << right << "ID"
                << setw(12) << "January"
                << setw(12) << "Febuary"
                << setw(12) << "March"
                << setw(12) << "April"
                << setw(12) << "May"
                << setw(12) << "June"
                << setw(12) << "July"
                << setw(12) << "August"
                << setw(12) << "September"
                << setw(12) << "October"
                << setw(12) << "November"
                << setw(12) << "December" << endl;

        for (unsigned int i = 0; i <= list.size(); i++)
        {
            outfile << setw(6) << right << list[i]; //i don't understand why it says there's an error here.
            for(int j = 0; j <= 11; j++)
                outfile << setw(12) << right << list[i][j];
            outfile << endl;
        }
    }
    outfile.close();
}

我已经尝试删除它并粘贴我上面编写的有效但仍然会出错的内容。

以下是错误消息:

   D:\QT\Salesperson\main.cpp:295: error: cannot bind 'std::basic_ostream<char>' lvalue to 'std::basic_ostream<char>&&'
         outfile << setw(6) << list[i];
                ^

对于文本文件,它有2行,1表示标题,另一行的值都设置为0

3 个答案:

答案 0 :(得分:2)

由于您using namespace std未将list声明为对象,因此您可能会影响此类名称。或者更好的是,由于这个问题,请不要使用using namespace std

但你的问题不会就此止步,看看这一行:

outfile<<setw(6)<<right<<list[i];

listvector< vector<float> >所以list[i]将解析为vector<float>,你如何打印出来?

在这一行:

for (unsigned int i=0; i<=list.size();i++)

应为i < list.size(),当i == list.size()时会发生什么,您将引用将调用未定义行为的vector[vector.size()] (请记住,数组引用从0开始)。

也可能有其他事情。

答案 1 :(得分:2)

outfile<<setw(6)<<right<<list[i]; //i don't understand why it says there's an error here.

因为std::vector<float>没有流插入器。

另请注意,for(unsigned int i = 0; i <= list.size(); ++i)将在列表末尾运行。使用<代替<=

答案 2 :(得分:-1)

非常感谢您指出我的代码中的错误,请原谅我,因为我刚刚开始。

for (unsigned int i=0; i<list.size();i++)
{
    outfile<<setw(6)<<right<<list[i][0];
    for(int j = 1; j<13; j++)
        outfile<<setw(12)<<right<<list[i][j];
    outfile<<endl;
}

我已经承认了每个人都指出的错误,并将部分代码改成了这个。现在非常感谢你了!

是什么让我失望的是错误指向&lt;&lt;这让我不知道列表上的内容是如何写错的。

相关问题