为是/否用户提示执行while循环

时间:2013-01-31 04:20:27

标签: c loops do-while

我找到素数因子的程序全部设定......我唯一需要做的就是这种类型的输出:

你想尝试另一个号码吗?说Y(es)或N(o):y //请求另一个号码(再次通过该程序)

你想尝试另一个号码吗?说Y(es)或N(o):n //感谢您使用我的程序再见!

我在下面尝试了这个...当我输入n时它会输出正确的输出。但是,如果我输入'y'它只是说同样的事情n ....我怎么能循环整个程序而不把程序的代码放在这个while循环中?所以,当我按y时,它再次通过程序?

int main() {
  unsigned num;
  char response;

  do{
    printf("Please enter a positive integer greater than 1 and less than 2000: ");
    scanf("%d", &num);
    if (num > 1 && num < 2000){
      printf("The distinctive prime facters are given below: \n");
      printDistinctPrimeFactors(num);
      printf("All of the prime factors are given below: \n");
      printPrimeFactors(num);
    }
    else{
      printf("Sorry that number does not fall within the given range. \n");
    }
    printf("Do you want to try another number? Say Y(es) or N(o): \n");
    response = getchar();
    getchar();
  }
  while(response == 'Y' || response == 'y');
  printf("Thank you for using my program. Goodbye!");

  return 0;
} /* main() */

4 个答案:

答案 0 :(得分:3)

问题可能是,你从y得到的东西不是getchar并且循环退出,因为条件不匹配。

getchar()可以使用缓冲区,因此当您键入“y”并按Enter键时,您将获得char 121(y)和10(输入)。

尝试以下程序,看看你得到了什么输出:

#include <stdio.h>

int main(void) {
    char c = 0;

    while((c=getchar())) {
        printf("%d\n", c);
    }
    return 0;
}

你会看到这样的事情:

$ ./getchar 
f<hit enter>
102
10

你可以看到键盘输入是缓冲的,下一次运行getchar()就可以得到缓冲的换行符。

编辑:就您的问题而言,我的描述只是部分正确。您可以使用scanf来读取您要测试的号码。所以你这样做:数字,输入,y,输入。

scanf读取数字,将输入中的换行符留在缓冲区中,response = getchar();读取换行符并将换行符存储在response中,下次调用getchar() (删除我上面描述的换行符)获取'y'并退出循环。

您可以通过让scanf读取换行符来解决此问题,因此它不会留在缓冲区中:scanf("%d\n", &number);

答案 1 :(得分:2)

使用scanf读取输入时(当您输入上面的数字时),按下返回键后会读取输入,但返回键生成的换行不会被scanf消耗。

这意味着你第一次调用getchar()将返回换行符(仍然位于缓冲区中),这不是'Y'。

如果您将两次调用反转为getchar() - 其中第二个是您为变量指定的调用,那么您的程序将起作用。

printf("Do you want to try another number? Say Y(es) or N(o): \n");
getchar(); // the newline not consumed by the scanf way above 
response = getchar();

答案 2 :(得分:0)

在你的getchar()陈述之后放scanf,这将从缓冲区中吃掉不必要的'\n' ...

答案 3 :(得分:0)

正如其他人所说,在你之前调用scanf()时遗留的输入流中只有一个'\ n'字符。

幸运的是,标准库函数fpurge(FILE * stream)擦除了给定流中缓冲的任何输入或输出。当你在调用scanf()和getchar()之间放置任何地方时,以下内容将清除stdin中缓冲区中的任何内容:

fpurge(stdin);
相关问题