[英]Access violation error when using QTextStream to read from console
我有問題,嘗試使用QTextStream進行數據讀取或寫入控制台時遇到訪問沖突 :
ApplicationStub.exe中0x77BD1D76(ntdll.dll)處的首次機會異常:0xC0000005:
訪問沖突寫入位置0x00000014。ApplicationStub.exe中0x77BD1D76(ntdll.dll)處未處理的異常:0xC0000005:
訪問沖突寫入位置0x00000014。
我的程序很簡單:
#include <QtWidgets/QApplication>
#include <iostream>
#include <QTextStream>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
///////////////////////////////////////////////CONSOLE
QTextStream out(stdout);
out << "Please enter login username and password\n";
out.flush();
QTextStream in(stdin);
QString line;
in >> line;
return app.exec();
}
可能是什么問題呢? 謝謝
編輯1我也嘗試過QCoreApplication我正在使用Visual Studio 2013,Windows 7
同樣在我的.pro文件中,我有:
QT += console
QT += core gui
我有GUI選項的gui,我認為應該沒問題。
盡管可以清除很多代碼,但是代碼根本沒有問題。 您很可能沒有將其構建為控制台應用程序,因此它在沒有控制台的情況下啟動,並且任何訪問不存在的控制台的嘗試都會失敗。
評論:
Class
,請使用#include <QClass>
,而不要使用#include <QtModule/QClass>
。 #include <QtCore>
就足夠了。 QCoreApplication
實例即可使用QTextStream
(請注意, QApplication
是QCoreApplication
!)。 stdout
和stdin
來自<cstdio>
標頭。 您不需要<iostream>
。 core
以外的任何模塊,則無需顯式添加core
模塊,因為所有其他模塊都依賴於它。 如果您在Qt 5中添加了widgets
模塊,則無需添加gui
模塊。 等等。 有兩種方法可以將控制台分配給您的進程:
將CONFIG += console
添加到qmake項目文件中。 這樣,您的進程在啟動時將始終具有控制台窗口:
# test1.pro QT = core CONFIG += console c++11 CONFIG -= app_bundle TARGET = test1 TEMPLATE = app SOURCES += main.cpp
您的代碼現在可以正常工作:啟動時,您會看到一個控制台窗口。
在GUI應用程序中明確分配控制台。 控制台窗口僅在需要時顯示,默認情況下不顯示:
# test1.pro QT = widgets # or core if you don't care for a graphical interface CONFIG += c++11 TARGET = test1 TEMPLATE = app SOURCES += main.cpp
main.cpp :
#include <QtCore> #include <cstdio> #include <windows.h> void addConsole() { AllocConsole(); freopen("CON", "wt", stdout); freopen("CON", "wt", stderr); freopen("CON", "rt", stdin); } int main() { addConsole(); QTextStream out{stdout}; QTextStream in{stdin}; out << "Enter your name: " << flush; QString name; in >> name; out << "Your name is: " << name << "." << endl; QThread::sleep(1); }
對項目文件進行任何更改后,您需要重新運行qmake 並重建項目。
為了簡化此過程,只需刪除構建文件夾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.