C++:ostream << 运算符错误

C++: Error on ostream << operator

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

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 行用于 header,另一行的值全部设置为 0

由于您 using namespace std 不要将 list 声明为对象,因此您很可能隐藏了这个 class 名称。或者更好的是,不要因为这个问题而使用 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 开始)。

可能还有其他的。

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) 会 运行 离开列表的末尾。使用 < 而不是 <=.

非常感谢您指出我代码中的错误,我才刚刚起步,请见谅。

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;
}

我已经把大家指出的错误改成了这个one.It现在可以用了非常感谢!

让我失望的是指向 << 的错误,这让我看不出 list 是如何写错的。