【发布时间】:2020-02-15 19:10:53
【问题描述】:
当我运行下面的代码时,它会正确执行,但会在我再次输入之前添加一个额外的迭代。不知道为什么。我将使用它来为孩子分叉和管道父进程。该步骤将在用户输入进程数之后进行。
代码:
#include <stdio.h>
int main(void) {
int num_processes;
int running = 1;
do {
printf ("How many processes do you want? (1, 2 or 4) \n");
num_processes = getchar();
num_processes -= '0';
if(num_processes == 1 || num_processes == 2 || num_processes == 4){
int temp = num_processes - 1;
printf("\n1 Parent and %d child processes\n", temp);
printf("----------------------------------\n");
running = 0;
} else {
printf("Invalid Input, please try again.\n");
}
} while(running == 1);
// Do important stuff
return(0);
}
输出:
How many processes do you want? (1, 2 or 4)
3
Invalid Input, please try again.
How many processes do you want? (1, 2 or 4)
Invalid Input, please try again.
How many processes do you want? (1, 2 or 4)
2
1 Parent and 1 child processes
----------------------------------
【问题讨论】:
-
对
getchar()的第二次调用返回一个换行符。 -
如果你想读行,使用
fgets(),而不是getchar()。