c程序不起作用scanf char

#include  int main() { struct cerchio c1, c2; float distanza; char k; //input del centro del primo cerchio printf("Enter the coordinate x of the first circle's center: "); scanf("%f", &c1.centro.x); printf("Enter the coordinate y of the first circle's center: "); scanf("%f", &c1.centro.y); //input del raggio del cerchio printf("Enter the circle's radius: "); scanf("%f", &c1.raggio); printf("The first circle's center is: (%.2f, %.2f)\n", c1.centro.x, c1.centro.y); printf("Do you want to move this circle? y/n \n"); //Here is the problem <------------- scanf("%s", &k); if(k=='y'){ moveCircle(&c1); printf("Now the circle's center is: (%.2f, %.2f)\n", c1.centro.x, c1.centro.y); } } 

在注释中的scanf //这里是问题,如果我把%c放在程序结束。 输入不起作用! 如果我把%s程序完美地运行起来。 为什么? 我已声明变量k char!

 scanf("%s", &k); 

应该

 scanf(" %c", &k); 

%c是字符( char )的正确格式说明符,而%s用于字符串。 %c后面的空格字符跳过所有空格字符,包括无,直到C11标准中指定的第一个非空白字符:

7.21.6.2 fscanf函数

[…]

  1. 由白色空格字符组成的指令通过读取第一个非空白字符(仍然未读取)的输入来执行,或者直到不再能够读取字符为止。 该指令永远不会失败

当您使用%c时,程序不会等待进一步输入的原因是因为标准输入流( stdin )中存在换行符( \n )。 记住在输入每个scanf数据后按Enter键scanf 不会使用%f捕获换行符。 而是由scanf使用%c捕获此字符。 这就是为什么这个scanf不等待进一步输入的原因。

至于为什么你的其他scanf%f )没有消耗\n是因为%f跳过了空格字符,如C11标准所示:

7.21.6.2 fscanf函数

[…]

  1. 除非规范包含[cn说明符,否则将跳过输入的空白​​字符(由isspace函数指定)。 284

至于你使用的程序工作原因是因为你很幸运。 使用%s而不是%c调用未定义的行为 。 这是因为%s匹配一系列非空白字符,并在末尾添加一个NUL终止符。 一旦用户输入任何内容,第一个字符将存储在k而其余字符(如果有)以及\0将写入无效的内存位置。

如果你正在考虑为什么%s格式说明符没有消耗\n是因为它跳过空白字符。

使用

 scanf(" %c",&k); 

代替

 scanf("%s", &k); // %s is used for strings, Use %c for character variable. 

for char变量使用“%c”。 并且不要忘记在%c " %c"之前保留空格,它会跳过换行符和空白字符。