Mo Kanj
Mo Kanj

Reputation: 127

Qt: How do I write data immediately to a QProcess?

My QProcess is very simple and goes something like:

#include <iostream>
#include <string>

int main() {
std::string a, b;
std::cout<<"Enter value of a: ";
std::cin>>a;
std::cout<<std::endl;
std::cout<<"Now, enter value of b: ";
std::cin>>b;
std::cout<<std::endl;
std::cout<<"Value of a is "<<a<<" and value of b is "<<b<<std::endl;

return 0;
}

Note that I cannot change the above code. The Qt code should work regardless of the process.

So as far as I understood, QProcess::write(const char *data) [inherited from QIODevice] sends the data to the buffer but does not directly send it to the standard in, unless the write channel is closed, or the process has finished.

However, I need to send data to the standard in directly as I call QProcess::write(const char *data), because I cannot close the channel after the first std::cin, or else the second std::cin does not get anything. So I want to send the process some data as it asks for it [as if running this code on a command line], and I'm not sure how to do that with Qt.

Also, I don't think waitForBytesRead()would do good since it just waits aroundupon entering the first set of data to the buffer and the process is not continued.

QProcess-related code:

  QProcess my_proc = new QProcess();
  QString program = "powershell.exe";
  QStringList prog_args;
  prog_args << "-Command" << "./main"
  my_proc->setProcessChannelMode(QProcess::MergedChannels);
  my_proc->setProgram(program);
  my_proc->setArguments(prog_args);
  my_proc->start();
  my_proc->waitForStarted();

~The output of the program gets printed on a QTextBrowser, or any similar widget. So I know when it asks for the relevant inputs.~

~In another QTextEdit qinput or similar, I input the string I want to send to the process, and this is governed by:

if ( my_proc->state() == QProcess::Running) {
my_proc->write(qinput->toPlainText().toStdString().c_str());
}

~And from here nothing happens, so the line "Now enter the value of b" does not get displayed~

Upvotes: 0

Views: 1504

Answers (2)

Vladimir Bershov
Vladimir Bershov

Reputation: 2832

No need to use ...toStdString().c_str() for such a cases when having QString and QByteArray.

Do the following:

if ( proc->state() == QProcess::Running) 
{
    proc->write(qinput->toPlainText().toUtf8() + "\n"); // as I understand, \n will flush the line
}

Note that you can also use proc->write("\n"); to simulate "press any key"

Upvotes: 2

user14289352
user14289352

Reputation:

you can try flushing stdin stream:

fflush(stdin);

or use getline:

std::string myString;
std::getline(std::cin, myString);

this will end reading when (newline char) is typed

Upvotes: 0

Related Questions