Mike Henderson
Mike Henderson

Reputation: 2132

Redirect stdin to stdout

Let's say I have a trivial C program that adds 2 numbers together:

#include <stdio.h>

int main(void) {
    int a, b;
    printf("Enter a: "); scanf("%d", &a);
    printf("Enter b: "); scanf("%d", &b);

    printf("a + b = %d\n", a + b);
    return 0;
}

Instead of typing into the termnial every time it executes, I enter the values of a and b into a file:

// input.txt
10
20

I then redirect stdin to this file:

./a.out < input.txt

The program works but its output is a bit messed up:

Enter a: Enter b: a + b = 30

Is there a way to redirect stdin to stdout so the output appears as if a user typed the values manually, ie:

Enter a: 10
Enter b: 20
a + b = 30

Upvotes: 3

Views: 376

Answers (2)

pmg
pmg

Reputation: 108967

Forget prompting; try this:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int a, b;
    if (scanf("%d%d", &a, &b) != 2) exit(EXIT_FAILURE);
    printf("%d + %d = %d\n", a, b, a + b);
    return 0;
}

You may want to find a way to allow your users to know what the executable is about, maybe adding command-line options?

$ echo "10 20" |./a.out
10 + 20 = 30

$ ./a.out --help
Program reads two integers and displays their sum

$

Upvotes: 0

Nick ODell
Nick ODell

Reputation: 25190

You could use expect for this. Expect is a tool for automating interactive command-line programs. Here's how you could automate typing those values in:

#!/usr/bin/expect
set timeout 20

spawn "./a.out"

expect "Enter a: " { send "10\r" }
expect "Enter b: " { send "20\r" }

interact

This produces output like this:

$ ./expect     
spawn ./test
Enter a: 10
Enter b: 20
a + b = 30

There are more examples here.

Upvotes: 6

Related Questions