2

I have the following C Program

#include <stdio.h>


int main()
{

    char a[200];
    a[199] = 0;


    printf("Enter some input ->\n");
    scanf("%s"  ,a);

    printf ("\nInput was %s\n", a);

    return 0;
}   

and I'm trying to write some input into it the following way:

from subprocess import *
a = Popen(["my_prog.elf", stdin=PIPE) 
a.stdin.write("MyInput")

yet this doesn't appear to work.... any ideas how to fix this?

** edit **

does anyone have any clue why a.stdin.flush() wont work?

1 Answer 1

2

scanfreads one whole line, until it reads the new line character \n, so you have to send this, too:

from subprocess import Popen, PIPE
a = Popen(["my_prog.elf"], stdin=PIPE) 
a.stdin.write("MyInput\n")

flush is only needed, if your output stream (stdin) is buffered (which pipes are not, by default). Even then, you need \n to terminate the line.

Sign up to request clarification or add additional context in comments.

4 Comments

** edit ** wow.... this apparently worked for some reason............. any idea why flush didn't work and this did?
Work's for me. What have you done exactly and who do you know, it doesn't work?
Basically im writing into stdin and having prints of what I wrote with stdin, so when trying to use flush it failed unfortunately..... @Daniel
Well, actually, scanf("%s" ...) reads one whole line, simply because that's how a "string" is defined to scanf. Technically, it would be more correct to say that scanf reads up until the first character that is incompatible with the data type specified by the format flags it's currently processing - e.g. it would stop at the first non-decimal-digit for %d...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.