【问题标题】:C - Do While adding extra StepC - 添加额外步骤时执行
【发布时间】: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()

标签: c io do-while getchar


【解决方案1】:

想想当你给出第一个输入时会发生什么。您输入 3,然后按 Enter。

现在,在标准输入缓冲区中,有两个项目等待使用,3\n(即 Enter)。

你第一次进入循环体,消耗了 3。现在下一个排队等待\n...

当您再次(第二次)进入循环体时,标准输入缓冲区要读取的下一个字符是\n,这就是第二个getchar() 愉快地返回给您的字符。

这是一个快速修复:

do {
    printf ("How many processes do you want? (1, 2 or 4) \n");
    // Eat trailing newline character, if any
    do {
      num_processes = getchar();      // read a character
    } while(num_processes == '\n');   // if it was the newline character, repeat
                                      // until `num_processes` is not the newline character

    // Continue with your logic..
    num_processes -= '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) 
2

1 Parent and 1 child processes
----------------------------------

PS:正如@Barmar 评论的那样,如果您想阅读行,请使用fgets()。在这里阅读更多:How to use fgets() to control the execution of while loop through user input in c?

【讨论】:

  • 我将修复我的代码以使用 fgets()。不知道这样更好。谢谢!
  • @Travis 不客气,我喜欢你的热情,所以我用这个link 编辑了我的问题,它展示了你在使用fgets() 时得到的几乎相同的行为。请务必检查出来!
  • 你是最棒的!我很感激这些信息!再次感谢! @gsamaras
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-28
  • 2019-05-12
  • 2016-10-09
  • 2019-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多