【问题标题】:My code repeats more than requried while loop我的代码重复了超过所需的 while 循环
【发布时间】:2014-03-13 06:47:17
【问题描述】:

问题是当我输入除yn 之外的任何字符时,它会显示此消息两次而不是一次)

This program is 'Calculator'
Do you want to continue?
Type 'y' for yes or 'n' for no 
invalid input 

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

void main ()
{
//program
//first to get two numbers 
//second to get choice

int x=0,y=0,n=0;
char choice;

//clrscr(); does no work in devc++
system("cls"); //you may also use system("clear");

while(x==0)
{

    puts("\t\tThis program is 'Calculator'\n\n");
    puts("Do you want to continue?");
    puts("Type 'y' for yes or 'n' for no ");
    scanf("%c",&choice);
    x++;



    if(choice=='y')
    {
        y++;
        puts("if this worked then we would continue to calculate the 2 no");
    }
    else if(choice=='n')
        exit(0);
    else
    {
        puts("invalid input");
        x=0;
    }


    }
getch();

    }

`

【问题讨论】:

  • 好吧,您基本上是在说“无效输入”,然后再次提示它们,这似乎是基于您编写的代码的预期行为。
  • 但对我来说它提示两次而不是一次

标签: c while-loop dev-c++


【解决方案1】:

它循环了两次,因为 enter(\n) 字符存储在缓冲区中,像这样使用 scanf(在 %c 之前添加空格)

scanf(" %c",&choice);

【讨论】:

  • 成功了!但是一个简单的空间是如何做出改变的呢?我是新手
【解决方案2】:

这是因为在您输入yn 并按enter 键后尾随换行。

试试这个:

scanf("%c",&choice);
while(getchar()!='\n'); // Eats up the trailing newlines

【讨论】:

  • 我不明白?我没有写 while(getchar()!='\n');
【解决方案3】:

如果您输入除 'y' 或 'n' 以外的任何字符,控制输入:

else
{
    puts("invalid input");
    x=0;
}

block,将 x 重置为 0,现在循环条件:

while(x == 0)

为真,因此再次进入循环。

您可能还想在阅读时跳过尾随的换行符:

scanf(" %c", &choice );

【讨论】:

  • 成功了!但是一个简单的空间是如何做出改变的呢?我是新手 ("%c",&choice);而不是 ("%c",&choice);
  • 第一次输入字符按回车,回车留在缓冲区中,只有字符被scanf消耗掉。因此,下一次循环时,尽管您正在输入一个字符,但 scanf 会使用输入缓冲区中的第一个字符,这是一个换行符。格式字符串中 %c 之前的空格指示 scanf 跳过任何空白字符,直到找到第一个实际字符。所以跳过换行符并读取实际字符。
  • 我的 c 书 (niit) 中从未教授过这个概念。他们只教我 fflush(stdin);这也有效。
  • 所以当我输入回车是否意味着\n?
  • Enter 是换行符。 fflush(stdin) 也可以工作,因为它会刷新输入流缓冲区。因此,如果您在第一次读取后调用 fflush(stdin),缓冲区中的换行符将被刷新,因此它会正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
  • 2013-01-29
  • 1970-01-01
相关资源
最近更新 更多