2014-01-25 54 views
2

基本上我提出在QT C++写变量“name”的简单函数到.txt文件,然而每当我编译得到的错误消息:Qt的C++敌不过“运算符<<”流

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(); 
    } 
} 
+0

绝对没有需要在Qt代码中使用'std :: string',除非你需要使用'std :: string'的第三方代码。使用'QString'。就这么简单。你会发现'QString'实际上有一个适用于许多真实世界用例的api,并且与处理'std :: string'所需的体操相比,生活更容易。 –

回答

6

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

例如:

stream << QString::fromStdString(name); 

QString::fromStdString docs

或者因为QTextStreamoperator<<const char*过载,你也可以这样做:

stream << name.c_str(); 
+0

这很有道理,谢谢! – user3183586

2

我不是一个qt人,但看起来像那里std::string

用途是no overload

stream << name.c_str();