我有一个 C 程序,它从命令行获取输入,处理输入,生成文件并终止。
例如 myprogram.c 类似:
int main(int argc, char *argv[])
{
//do something with the input
// and generate a file
exit(0);
}
我目前给出的输入为:
echo -n abcd | myprogram.c
我希望程序做的不是在一次输入后终止,而是应该继续执行并等待下一个控制台输入以生成下一个文件,依此类推。
有人可以指导我吗?
最佳答案
您可以使用while
循环:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool function(char *input)
{
// do something with the input
// and generate a file
// example:
if (strcmp(input, "exit") == 0)
return true;
printf("I did something with '%s'\n", input);
return false;
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Usage: program_name <argument>.");
return 1;
}
function(argv[1]);
bool exit = false;
while (!exit)
{
char input[32];
scanf("%s", &input);
exit = function(input);
}
return 0;
}
关于c - 如何让这个C函数连续执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58502687/