QtCreator 2.4.1 控制台输入

3

我对C++和QT还比较新手。

我试图在QtCreator中运行一个非常简单的程序,在WinXP上使用控制台输入:

#include <QString>
#include <QTextStream>

int main() {
    QTextStream streamOut(stdout);
    QTextStream streamIn(stdin);
    QString s1("This "), s2("is a "), s3("string.");
    QString s4 = s1 + s2 + s3;
    streamOut << s4 << endl;
    streamOut << "The length of that string is " << s4.length() << endl;
    streamOut << "Enter a sentence with whitespaces: " << endl;
    s4 = streamIn.readLine();
    streamOut << "Here is your sentence: \n" << s4 << endl;
    streamOut << "The length of your sentence is: " << s4.length() << endl;
    return 0;
}

问题是QTCreator的应用程序输出,由于它的名称,不支持输入内容。以下是应用程序输出:
Starting C:\QProject\test-build-desktop-Qt_4_8_0_for_Desktop_-MinGW_Qt_SDK__>>>\debug\test.exe... 这是一个字符串。 该字符串的长度为17 输入一个带有空格的句子: Qml调试已启用。只在安全环境中使用!
我尝试在“项目>桌面>运行”中检查“在终端中运行”,因为类似问题的一些答案在这里建议,终端出现了,但它似乎无论如何都不与程序交互。终端输出:
按ENTER关闭此窗口...

1
你能把 cincout 放在主函数的作用域中看看是否有所不同吗?(一般来说,这不是最好的命名想法,人们会认为它们是 std::cin/out。) - Mat
是的,我尝试让我的问题更清晰,谢谢。 - user1230585
1个回答

2
我认为勾选“在终端中运行”是正确而必要的。
令人惊讶的是,您没有收到任何编译错误,因为第8行存在错误:
cout << "Enter a sentence: "<<;

最后一个<<是错误的。
修正您的代码后,我得到了这个:
#include <QString>
#include <QTextStream>
QTextStream cout(stdout);
QTextStream cin(stdin);

int main() {
    QString s2;
    cout << "Enter a sentence: ";
    s2 = cin.readLine();
    cout << "Here is your sentence:" << s2 << endl;
    cout << "The length of your sentence is: " << s2.length() << endl;
    return 0;
}

这段代码在我的电脑上(WinXP,QtCreator 2.2.0)运行良好。

你确定你的Qt项目是正确的,并且你正在编译正确的文件吗?


cout << "Enter a sentence: "; 之后添加 cout.flush(); ... 无论如何,我只需要在我的项目文件中添加 CONFIG += console,控制台就可以正常工作了。 - user1230585

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接