首页 > 解决方案 > 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价值。

我想知道为什么以及是否有其他与书中示例不同的方法来实现它?

感谢您的时间!

标签: c

解决方案


嗨,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
    }
}

不要忘记选择一个您认为是解决问题的最佳方法的答案。


推荐阅读