C语言char变量scanf输入报错:格式符与参数类型不匹配
问题解决:scanf读取char变量的警告与输入异常
核心问题1:scanf参数类型不匹配
你遇到的警告根源很明确——使用%c格式符调用scanf时,必须传递变量的地址,而非变量本身。
scanf的工作逻辑是通过指针修改外部变量的值,所以对于int、double、char这类基本数据类型,都需要在变量前加&取地址符。你原来的代码:
scanf("%c", namehumaninput);
要改成:
scanf("%c", &namehumaninput);
核心问题2:输入缓冲区残留的换行符
就算改了地址,你大概率会发现程序直接跳过名字输入——这是因为前面输入年龄、GPA时,你按下的回车键(换行符\n)会留在输入缓冲区里,后面的%c会直接读取这个换行符,而非你手动输入的字符。
解决这个问题有两种简单方案:
- 在
%c前加一个空格,让scanf自动跳过所有空白字符(包括换行、空格、制表符):scanf(" %c", &namehumaninput); - 或者在读取名字前,用
getchar()手动吃掉残留的换行:// 在scanf读取名字前插入这一行 getchar(); scanf("%c", &namehumaninput);
修正后的完整代码片段
//Lesson 9 int inputage; double gpainput; char namehumaninput; printf("Wat ur age?\n"); scanf("%d", &inputage); // scanf(); is how you do an input. You MUST have & behind a variable after a %d!! printf("You are %d years old\n", inputage); printf("Was yo GPA?\n"); scanf("%lf", &gpainput); // %lf is for double variables when using scanf() but using printf() it uses %f for doubles, not %s. printf("Your GPA is %f\n", gpainput); printf("Wos yo name now that ive asked yo fo yo gpa and age\n"); // 修正:添加&取地址符,加空格跳过空白字符 scanf(" %c", &namehumaninput); printf("Really? Yo name is %c?\n", namehumaninput);
另外提个小细节:你注释里说printf用%s打印double是错误的,printf打印double用%f即可,%s是用来打印字符串的。
内容的提问来源于stack exchange,提问作者Skibi OS
相关产品推荐
相关产品推荐

