C语言使用scanf函数实现6字母回文检测时输入异常问题求助
问题原因
该问题由scanf函数%c格式符的读取特性导致:%c不会自动跳过输入缓冲区中的空白字符(换行符、空格、制表符均属于空白字符)。你每输入一个字母后按下的回车键,会生成一个\n字符存储在输入缓冲区,被后续的%c当做有效字符读取。
举个例子:你输入第一个字母a后按回车,输入缓冲区会依次存入a、\n两个字符,前者被第一个scanf读取到l1,后者直接被第二个scanf读取到l2。以此类推,每输入1个字母+1次回车会消耗2个%c的读取配额,所以你输入3个字母加3次回车后,6个scanf就已经全部读取到了内容,程序就会直接执行后续的反转输出逻辑。
修复方案
方案1:修改
%c格式符,自动跳过空白字符
在每个scanf的%c前添加一个空格,空格会指示scanf自动跳过读取位置前所有的空白字符,仅将输入的有效字母读取到变量中,修改后的代码段如下:#include <stdio.h> int main() { char l1, l2, l3, l4, l5, l6; printf("Enter a 6-letter word\n"); scanf(" %c", &l1); scanf(" %c", &l2); scanf(" %c", &l3); scanf(" %c", &l4); scanf(" %c", &l5); scanf(" %c", &l6); printf("Let's see if this word is a palindrome. The reversed word is: %c%c%c%c%c%c", l6, l5, l4, l3, l2, l1); // 可补充回文判断逻辑:l1==l6 && l2==l5 && l3==l4 即为回文 return 0; }方案2:用字符数组批量读取输入,简化逻辑
你可以直接用长度为7的字符数组存储6字母单词(额外1位存储字符串结束符\0),不需要拆分单个变量读取,同时可直接补充回文判断逻辑,示例代码如下:#include <stdio.h> #include <string.h> int main() { char word[7]; printf("Enter a 6-letter word\n"); scanf("%6s", word); if (strlen(word) != 6) { printf("输入错误,请输入恰好6个字母的单词\n"); return 1; } printf("Let's see if this word is a palindrome. The reversed word is: %c%c%c%c%c%c\n", word[5], word[4], word[3], word[2], word[1], word[0]); if (word[0] == word[5] && word[1] == word[4] && word[2] == word[3]) { printf("该单词是回文\n"); } else { printf("该单词不是回文\n"); } return 0; }
内容的提问来源于stack exchange,提问作者Kausthubha RS
相关产品推荐
相关产品推荐

