Qt C ++与'operator<<'不匹配流

时间:2014-01-25 15:45:07

标签: c++ qt

基本上我在QT C ++中创建了一个简单的函数来编写变量" name"到.txt文件,但每当我编译时,我收到一条错误消息:

no match for 'operator<<' (operand types are
'QTextStream' and 'std::string 
{aka std::basic_string<char>}')
         stream << name;

我已经多次查看了这条线,但我不知道发生了什么,我的错误的任何输入都将非常感激。

功能代码:

void Write()
{
    std::string name;
    QFile file("C:/Users/brandan/Desktop/GUIPrograms/Kumon.txt");

    if(file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QTextStream stream(&file); //stream of information
        stream << name;

        stream.flush();
        file.close();
    }
}

2 个答案:

答案 0 :(得分:6)

Qt流类不直接处理std::string。您需要将其转换为QString才能将其与QTextStream一起使用。

例如:

stream << QString::fromStdString(name);

QString::fromStdString docs

或者由于QTextStream的{​​{3}} const char*超载,您也可以这样做:

stream << name.c_str();

答案 1 :(得分:2)

我不是qt人,但std::string

看起来no overload

使用:

stream << name.c_str();