簡體   English   中英

將標准輸入重定向到標准輸出

[英]Redirect stdin to stdout

假設我有一個簡單的 C 程序,它將 2 個數字加在一起:

#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;
}

我沒有在每次執行時都輸入終端,而是將ab的值輸入到文件中:

// input.txt
10
20

然后我將stdin到這個文件:

./a.out < input.txt

該程序有效,但它的 output 有點混亂:

Enter a: Enter b: a + b = 30

有沒有辦法將標准輸入重定向到標准輸出,所以 output 看起來好像用戶手動鍵入了值,即:

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

您可以為此使用期望。 Expect 是一個自動化交互式命令行程序的工具。 以下是您可以如何自動輸入這些值:

#!/usr/bin/expect
set timeout 20

spawn "./a.out"

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

interact

這會產生 output ,如下所示:

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

這里有更多的例子。

忘記提示; 嘗試這個:

#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;
}

您可能想找到一種方法讓您的用戶知道可執行文件的內容,也許是添加命令行選項?

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

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

$

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM