Home > Mobile >  How to send input to stdin from code not terminal?
How to send input to stdin from code not terminal?

Time:08-07

I want to send input to a variable without having to type it in the terminal, as i am implementing a test case. for example consider the input to be sent is 2:

int a;
cin >> a;

The code should not wait for the user to give input, it should enter 2 there and populate a by itself.

i cant use the cin buffer, also taking input is compulsory.

CodePudding user response:

you could create unnamed pipes pipe pd[2] and dup stdin & stdout to the pipe fds. then write "2" into one pipe and read it from another.

CodePudding user response:

You can get your input from a stringstream instead:

std::stringstream data = "2";
int a;
data >> a;

CodePudding user response:

The basic question here (at least in my mind) is whether you're trying to write a single program, so that one part of the program provides the input to another part of the program, or you're writing two separate programs, one of which provides input to the other.

@Madhu Narayanan has already given a good summary of how you'd go about writing the code for the first case. But, by far the preferable way to handle things inside a program is to have something like a function that takes (a reference to) an iostream as a parameter, so you can pass std::cin to read from the console, or some stringstream to have it read some predetermined data instead.

If what you care about is the second case, then you'd probably want to use popen (or Microsoft calls it _popen), which will spawn a child process, and connect a pipe to either its standard input or its standard output (but, regrettably, not both). So if this is what you want you'd do something like this:

// spawn the child, getting a handle to its standard input:
FILE *child = popen("child program", "w");

// write the input to the child:
if (child != nullptr) {
     fprintf(child, "%d", 2);
}

For better or worse, there's no analog of this that gives you access to the child via an iostream (at least, not a pre-written one in the standard library, anyway).

  •  Tags:  
  • c
  • Related