c - C程序,获取字符的整数值。为什么在第 10 行之后一切都出来了?
问题描述
嗨,我是编程新手,当我尝试对书中的示例进行一些更改时遇到了麻烦。
/* Chapter 3 Example, C Prime Plus */
#include <stdio.h>
int main(void)
{
char Letter, ch;
int intValue;
printf("Please enter a letter: \n");
scanf("%c", &Letter); /* user inputs character */
printf("The code for %c is %d.\n", Letter, Letter);
printf("Now is another we to implement the process: \n");
printf("RN, the value of ch is %c, and the value of intValue is %d\n", ch, intValue);
printf("Please enter a letter: \n");
scanf("%c", &ch);
intValue = ch;
printf("The code for %c is %d.\n", ch, intValue);
return 0;
}
当我运行它时,结果将是
请输入字母:
M M
的代码是 77。
现在是我们实现的另一个过程:
RN,ch 的值为 ,intValue 的值为 0
请输入字母:
代码为
10。
而
“现在是另一个我们要实现的过程:
RN,ch的值为,intValue的值为0
请输入字母:
代码为
10。”这部分会全部出来而不要求我输入a价值。
我想知道为什么以及是否有其他与书中示例不同的方法来实现它?
感谢您的时间!
解决方案
嗨,Matt_C,欢迎来到 SO。
首先,您不需要第二组 printfs 和 scanf,它只是试图做同样的事情并且存在顺序错误。
其次,当您尝试连续 scanf 时会很棘手,它会保留最后按下的键(回车是按下的最后一个键 = \n)。这就是它跳过第二个 scanf 的原因。
有一个小解决方案,在 scanfs 的开头添加一个空格。试试这个:
int main() {
char exit, letter;
while (1) {
printf("Please enter a letter: ");
scanf(" %c", &letter);
printf("\nThe code for '%c' is %d. \n\n", letter, letter);
printf("Exit ? (y/n): ");
scanf(" %c", &exit);
if(exit == 'y')
{
break;
}
system("clear"); // UNIX
//system("cls"); // DOS
}
}
不要忘记选择一个您认为是解决问题的最佳方法的答案。
推荐阅读
- c# - 在 C# 中的应用程序中安全地存储密码
- electron - 为什么 electron-osx-sign 无法生成 Gatekeeper 识别的签名应用程序?
- javascript - 如何计算动态创建的项目和数量 JQuery
- javascript - Javascript参数是否必要?
- logging - 如何在记录器 xml 标记内的 appender refs 中禁用 log4j2.xml 可加性
- java - 设置密钥库文件的相对路径
- c# - c# api方法动态创建
- c# - 属性是否隐式初始化变量?
- node.js - if语句中的NodeJS猫鼬错误
- reactjs - 反应路由器、重定向、firebase auth 和私有路由:管理它的最佳方式