C语言字符与ASCII码互转程序选字符转ASCII功能异常如何解决
问题原因
你的代码存在两个核心错误:
- 功能选项读取的格式符使用错误:你使用
%s格式符为单个char类型的option变量赋值,%s是字符串读取格式符,读取完成后会自动在目标内存末尾写入字符串结束符\0,会造成内存越界写入,属于未定义行为。 - 输入缓冲区残留换行符未处理:输入选项后按下的回车键会在输入缓冲区留下换行符
\n,%c格式符默认不会跳过空白字符,后续读取字符的scanf会直接读取这个残留的换行符,你输出的ASCII码10就是换行符的ASCII值。
修复方案
修改两处scanf的格式符,在%c前添加空格,让scanf自动跳过所有前置空白字符,同时将读取选项的格式符从%s改为%c匹配变量类型,修复后的完整代码如下:
#include <stdio.h> int main(void) { char option; printf("-------- MENU --------\n"); printf("1. Get ASCII code of a character.\n"); printf("2. Get character from ASCII code.\n"); printf(": "); // %c前加空格跳过前置空白,使用%c匹配char类型变量 scanf(" %c", &option); if (option == '1') { char character; printf("Enter a character: \n"); // 同样添加空格跳过残留的空白字符 scanf(" %c", &character); printf("The character you entered: %c\n", character); printf("ASCII code of %c is %d\n", character, character); } else if (option == '2') { int number; printf("Enter a Number: \n"); scanf("%d", &number); printf("The number you entered: %d\n\n", number); printf("The ASCII character with code %d is %c\n", number, number); } else { printf("Invalid Input !\n"); } return 0; }
内容的提问来源于stack exchange,提问作者Sarvesh M.D
相关产品推荐
相关产品推荐

