gpt4 book ai didi

c - bash 脚本 'here strings'

转载 作者:太空宇宙 更新时间:2023-11-04 01:15:48 25 4
gpt4 key购买 nike

我将从 bash 脚本中运行一个 C 程序。

c 程序需要来自用户的输入。输入总数为 7。它们位于 7 条不同的线上。例如

Please enter input1: 
1
Please enter input2:
2
Please enter input3:
3

等等..我做了一些阅读,发现 bash here strings 用于此目的。所以我使用以下命令从 bash 脚本中运行程序

./runnable <<< 1 

这解决了仅需要一次输入时的目的...需要多次输入时的解决方案是什么?

最佳答案

通常答案可能是“视情况而定”,但如果程序是这样的:

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

int main(int argc, char *argv[])
{
char s1[100], s2[100];
printf("Enter string1:");
fflush(stdout);
fgets(s1, sizeof(s1), stdin);
printf("Enter string2:");
fflush(stdout);
fgets(s2, sizeof(s2), stdin);
printf("string1: '%s', string2: '%s'\n", s1, s2);
exit(1);
}

然后您可以使用“此处的文档”语法为其提供输入:

$ ./a.out <<_END_ 
> string1
> string2
> _END_
Enter string1:Enter string2:string1: 'string1
', string2: 'string2
'

这种语法已经不仅仅是 shell,它还是 Perl 和 Ruby 中的一种方便的构造。

关于c - bash 脚本 'here strings',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1218044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com