使用Qt模板新建命令行项目并读取输入

使用Qt模板新建命令行项目并读取输入

新建Qt项目并选择命令行应用模板以新建命令行项目,但Qt新建的命令行模板main函数中仅包括一行QCoreApplication a (argc, argv) 和 return a.exec();

该程序模板并不能直接运行,需要在项目设置中勾选Run in terminal

要实现在终端输入输出内容,可以使用Qt的 QTextStream 类,也可以使用标准的c++终端,以下为两种方法示例。同时,将return a.exec()修改为a.exit(0); return 0;以退出终端。

#include <QCoreApplication>
#include <QTextStream>
#include <iostream>

using namespace std;

//使用Qt的QTextStream终端
void do_qt(){
    QTextStream qin(stdin);
    QTextStream qout(stdout);
    qout<<"Please input your name,for qt terminal test: ";
    qout.flush();
    QString name=qin.readLine();
    qout<<"Hello "<<name<<"\n";
    qout.flush();
}

//使用标准终端
void do_std(){
    string userName;
    cout<<"Please input your name, for std output test: ";
    cin>>userName;
    cout<<"Hello "<<userName<<"\n";
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    do_qt();
    do_std();
    a.exit(0);
    //退出程序
    return 0;
//    return a.exec();
} 
作者
魏智勇(John)
加入讨论

此站点使用 Akismet 来减少垃圾评论。了解我们如何处理您的评论数据

魏智勇(John)

站长,80后,创业者,擅长工业自动化与信息化技术,熟悉各种PLC,组态软件,熟悉计算机技术,熟悉LabVIEW、C,C#,JavaScript程序设计技术。