Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用%c时奇数循环不起作用_C_Scanf - Fatal编程技术网

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

使用%c时奇数循环不起作用,c,scanf,C,Scanf,我学习C语言编程。我在scanf()中使用%c时编写了一个奇怪的循环,但它不起作用 #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 : %

我学习C语言编程。我在
scanf()

中使用
%c
时编写了一个奇怪的循环,但它不起作用

#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);
    }
}
#包括
void main()
{
char另一个class='y';
int-num;
而(另一个=='y')
{
printf(“输入一个数字:\t”);
scanf(“%d”和&num);
printf(“%d的Sqare为:%d”,num,num*num);
printf(“\n是否要输入另一个数字?是/否”);
scanf(“%c”和另一个);
}
}

但是如果我在这个代码中使用
%s
,例如
scanf(“%s”和另一个),那么它工作正常。
为什么会发生这种情况?有什么想法吗?

在这种情况下,使用
getch()
而不是
scanf()
。因为scanf()需要“\n”,但您在该scanf()上只接受一个字符。因此“\n”被赋予next scanf(),导致混淆。

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

当您使用
%s
时,它会跳过任何前导空格以获取除空格以外的字符。它将新行视为空白,因此隐式跳过等待的新行。因为(大概)没有其他东西等待阅读,所以它继续等待您输入某些内容,正如您显然希望的那样

如果要使用
%c
进行转换,可以在格式字符串前面加一个空格,也可以跳过流中的任何空格。

\include
#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");
    getchar();
    scanf("%c", &another);
}
}
void main() { char另一个class='y'; int-num; 而(另一个=='y') { printf(“输入一个数字:\t”); scanf(“%d”和&num); printf(“%d的Sqare为:%d”,num,num*num); printf(“\n是否要输入另一个数字?是/否”); getchar(); scanf(“%c”和另一个); } }
在为第一次扫描%d输入一个数字后,回车键位于stdin流中。此密钥由scanf%c行捕获


使用
scanf(“%1s”,字符数组);另一个=字符数组[0]

当您输入
num
并按enter键时,enter的ascii码将存储在scanf缓冲区中,并且每当您读取下一个字符时,它都不会等待用户输入,
enter
ascii码将存储在
另一个
变量中。-1用于推荐。我的坏。。。编辑答案。