这个程序应该做的是问用户一个简单的算术问题,例如5 + 7 然后用“bc”检查答案(是否正确)。
我有以下代码,但我不明白如何编辑它以将“5 + 7”的结果存储到变量中(目前结果进入 STDOUT)。
欢迎任何帮助。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main( int argc, char *argv[], char *env[] )
{
char *expr = "5 + 7\n";
int answer;
printf("%s = ", expr);
scanf("%d", &answer);
int pfds[2];
pipe(pfds);
if (!fork()) {
close(1); /* close normal stdout */
dup(pfds[1]); /* make stdout same as pfds[1] */
close(pfds[0]); /* we don't need this */
printf("%s\n", expr);
/***********************/
/* How to store printf()'s output into a variable? */
exit(0);
} else {
close(0); /* close normal stdin */
dup(pfds[0]); /* make stdin same as pfds[0] */
close(pfds[1]); /* we don't need this */
execlp("bc", "bc", NULL);
}
return 0;
}
最佳答案
您需要创建第二个管道并在子进程中将 stdout
重定向到它。
关于c - 如何将 "bc"的输出存储到变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20325944/