繁体   English   中英

C程序不起作用scanf char

[英]c program doesn't work scanf char

#include <stdio.h>
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输入数据后按回车吗? scanf 不能使用%f捕获换行符。 该字符由scanf使用%c捕获。 这就是为什么此scanf不等待进一步输入的原因。

至于为什么其他scanf s(带有%f )不使用\\n的原因,是因为%f跳过了C11标准中所示的空白字符:

7.21.6.2 fscanf函数

[...]

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

至于为什么您的程序在使用时起作用,是因为您很幸运。 使用%s代替%c调用Undefined Behavior 这是因为%s与一系列非空白字符匹配,并在末尾添加了NUL终止符。 用户输入任何内容后,第一个字符将存储在k而其余的字符(如果有)以及\\0被写入无效的存储位置。

如果您当前正在考虑为什么%s格式说明符未使用\\n是因为它跳过了空白字符。

采用

scanf(" %c",&k);

代替

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM