使用%c,奇数循环不起作用

Jes*_*gmn 6 c scanf

我倾向于C编程.我写了一个奇怪的循环,但在我使用%c时不起作用scanf().
这是代码:

#include<stdio.h>
void main()
{
    char another='y';
    int num;
    while ( another =='y')
    {
        printf("Enter a number:\t");
        scanf("%d", &num);
        printf("Sqare of %d is : %d", num, num * num);
        printf("\nWant to enter another number? y/n");
        scanf("%c", &another);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我%s在这段代码中使用scanf("%s", &another);,那么它工作正常.
为什么会这样?任何的想法?

Jer*_*fin 10

%c转换读取输入的下一个字符,不管它是什么.在这种情况下,您之前使用过读取的数字%d.您必须按Enter键才能读取该数字,但是您还没有做任何事情来从输入流中读取新行.因此,当您进行%c转换时,它会从输入流中读取该换行符(无需等待您实际输入任何内容,因为已经有输入等待读取).

当您使用时%s,它会跳过任何前导的空白区域以获得除空白区域之外的某些角色.它将新行视为空白行,因此它会隐含地跳过等待的新行.因为(大概)没有其他东西等待阅读,所以它会等待你输入一些东西,就像你显然想要的那样.

如果要%c用于转换,可以在其前面加上格式字符串中的空格,该空格也将跳过流中的任何空白区域.


Jey*_*ram 1

在这种情况下使用getch()而不是scanf()。因为 scanf() 需要 '\n' 但您在该 scanf() 处只接受一个字符。所以 '\n' 给下一个 scanf() 导致混乱。