C语言新手求助:使用scanf结合指针处理输入输出时遇异常
问题分析与修复方案
你的代码核心问题出在scanf的格式字符串使用上,另外还有字符输入的缓冲区问题,下面一步步说明:
1. scanf格式字符串的错误
scanf的格式字符串中,除了格式说明符(比如%d、%c)和空白符之外的普通字符,要求用户输入的内容完全匹配。你写的:
scanf("Enter 3 Ints and 1 Char:%d %d %d %c", x, y, z, e);
会强制要求用户输入必须以Enter 3 Ints and 1 Char:开头,但你实际输入的是2 3 4 c,完全不匹配,导致scanf没有给任何变量赋值,输出的都是内存里的随机垃圾值。
正确的做法是用printf单独输出提示文字,scanf只保留格式说明符:
printf("Enter 3 Ints and 1 Char: ");
2. 字符输入的缓冲区问题
当你输入完三个整数并按下回车后,换行符会留在输入缓冲区中,后续的%c会直接读取这个换行符,而不是你输入的目标字符。解决方法是在%c前添加一个空格,让scanf自动跳过所有空白符(空格、换行、制表符等):
scanf("%d %d %d %c", x, y, z, e);
完整修正代码
#include <stdio.h> int main() { int a, b, c; char d; int *x = &a; int *y = &b; int *z = &c; char *e = &d; printf("Enter 3 Ints and 1 Char: "); scanf("%d %d %d %c", x, y, z, e); printf("The numbers are:\n"); printf("%d\n%d\n%d\n%c\n", a, b, c, d); return 0; }
额外优化建议
其实你不需要单独定义指针变量x、y、z、e,直接把变量的地址传给scanf即可,代码会更简洁易读:
#include <stdio.h> int main() { int a, b, c; char d; printf("Enter 3 Ints and 1 Char: "); scanf("%d %d %d %c", &a, &b, &c, &d); printf("The numbers are:\n"); printf("%d\n%d\n%d\n%c\n", a, b, c, d); return 0; }
内容的提问来源于stack exchange,提问作者Grandad Douglas
相关产品推荐
相关产品推荐

