scanf函数异常:无法获取并打印第二个输入整数的问题排查
问题分析与解决
你的问题根源在于第二个scanf的格式字符串中多了一个\n。
在scanf的格式规则里,空白字符(包括换行符\n、空格、制表符)会让函数跳过输入中所有连续的空白内容,直到遇到非空白字符才会停止等待。当你写scanf("%llu\n", &y);时,输入完第二个整数并按下回车后,scanf会继续等待你输入非空白字符,不会结束读取操作,程序也就无法执行后续的printf语句输出y的值——单独运行第二部分代码时,也是因为同样的原因导致失败。
修正后的代码如下:
#include <stdio.h> #include <math.h> int main (void) { unsigned long long int x = 0, y = 0; printf("The first integer: "); scanf("%llu", &x); printf("x is %llu\n", x); printf("The second integer: "); scanf("%llu", &y); // 去掉格式字符串里的\n printf("y is %llu", y); }
只需要把第二个scanf格式字符串中的\n删除,就能正常读取并输出第二个无符号长整型整数了。
内容的提问来源于stack exchange,提问作者nmn
相关产品推荐
相关产品推荐

