Read text from Windows console
-
Is there a way to get text from a windows console not in blocking mode?
(Without use std::cin.get) -
Without the cin use, nup, don't think so. Only when you make the terminal yourself and use QProcess or include it in your own program should that be possible. Why don't you want to use the cin?
-
Because cin is a blocking function.
I want to have an event when someone click on keyboard or verify if there is something (with a timer) to read before read.
That in a console application. -
Hi, if you're not planning porting your app to Linux/Macs you have a bonanza of oldstyle Win32 console API's to choose from. here's a simple example:
Create a Qt vanilla console app, erase everything in main.cpp and paste this in:
@
#include <iostream>
#include <conio.h>
#include <QDateTime>
#include <QThread>int main()
{
std::cout << "Type q to exit\n";for (;;) { if (_kbhit()) if ('q' == _getch()) exit(0); std::cout << QDateTime::currentDateTime().toString("ss").toStdString() << " "; QThread::sleep(1); }
}
@ -
Create a background thread like:
@class MyThread : public QThread
{
signals:
void inputReceived(const QString &text);
protected:
virtual void run(void);
};// ---------------
void MyThread::run(void)
{
for(;;)
{
char buffer[1024];
std::cin.get(buffer, 1024)
const QString text = QString::fromLatin1(buffer).trimmed();
if(!text.empty()) emit inputReceived(text);
}
}@ -
On Windows is perfect but on Linux I have to press q and then return. Can you suggest me the way to press only q on Linux?
On Windows:
@ #include "conio.h"
QString BufferIn; while (kbhit()!= 0) BufferIn.append(getch()); if (BufferIn.compare("q", Qt::CaseInsensitive)== 0) QCoreApplication::instance()->quit();@
On Linux:
@ #include "stdio.h"
#include <termios.h>
#include <sys/ioctl.h>int QCKeyboard::kbhit(void) { struct timeval tv; fd_set read_fd; tv.tv_sec= 0; tv.tv_usec= 0; FD_ZERO(&read_fd); FD_SET(0, &read_fd); if (select(1, &read_fd, NULL, NULL, &tv)== -1) return 0; if (FD_ISSET(0, &read_fd)) return 1; return 0; } QString BufferIn; while (kbhit()!= 0) BufferIn.append(getchar());@
-
Re. Linux, almost there: turn off the console buffering at app launch, like this:
@
struct termios ts;
tcgetattr(0, &ts);
ts.c_lflag &= ~ICANON; /* disable buffered i/o */
tcsetattr(0,TCSANOW,&ts);
@