【问题标题】:How can I store and print a character input?如何存储和打印字符输入?
【发布时间】:2021-12-23 09:28:05
【问题描述】:

我熟悉使用 getchar(); 存储和打印字符;和 putchar();。 但是,当我将它与我的整个代码一起使用时,它似乎不起作用。在命令窗口中,它将获取字符,但不打印。因此,我不知道计算机在做什么。我尝试了自己存储和打印字符的代码,效果很好。

int ans;
    printf("\n\t Would you like to remove an item from your cart? (Y or N): ");
    ans = getchar();
    printf("\n\t ");
    putchar(ans);

但是一旦我将它与整个代码一起使用,它就无法正常工作。

#include <stdio.h>  

void  main()
{
    float items[6];
    float sum;
    float taxSum;
    printf("\n\n\n\n");

    printf("\t Please enter the price for Item 1: ");
    scanf_s(" %f", &items[0]);
    while (!((items[0] >= 0.001) && (items[0] <= 999.99)))
    {
        printf("\n\t [ERROR] Please enter number between $0.01 and $999.99: ");
        scanf_s(" %f", &items[0]);
    }

    int ans;
    printf("\n\t Would you like to remove an item from your cart? (Y or N): ");
    ans = getchar();
    printf("\n\t ");
    putchar(ans);

我非常好奇为什么会这样,以及我需要做什么才能让它发挥作用。

【问题讨论】:

  • joelcodes "非常好奇" --> 在putchar(ans); 之前添加printf("%d\n", ans); 以查看您正在打印的int 的字符代码。是 10(换行)?
  • 旁注:对于基于行的用户输入,我建议您使用fgets 而不是scanfgetchar。有关详细信息,请参阅此页面:A beginners' guide away from scanf()

标签: c char whitespace getchar putchar


【解决方案1】:

使用

char ans;
printf("\n\t Would you like to remove an item from your cart? (Y or N): ");
scanf( " %c", &ans );
       ^^^^^

ans = toupper( ( unsigned char )ans );
putchar( ans );

查看格式字符串中的前导空格。它允许跳过空白字符,例如与按下的 Enter 键相对应的换行符 '\n'。

或者正如 @chux - Reinstate Monica 在他的评论中所写,而不是将变量 ans 声明为具有 char 类型,您可以使用 unsigned char 类型声明它。例如

unsigned char ans;
printf("\n\t Would you like to remove an item from your cart? (Y or N): ");
scanf( " %c", &ans );
       ^^^^^

ans = toupper( ans );
putchar( ans );

【讨论】:

  • 除此之外:可以使用unsigned char ans; 代替char ans; ... ( unsigned char ) 并且不进行强制转换。
  • 成功了!谢谢你。那么当使用 char 和用户输入时,前导空格是必要的吗?
  • 我//注释掉了 c = toupper( ( unsigned char )c );因为我不知道那是什么。但是,没有它它仍然有效。这是什么原因?
  • @joelcodes 这允许跳过空白字符。
  • @joelcodes 用户可以输入“y”而不是“Y”。该函数将小写字母转换为大写字母。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-10
相关资源
最近更新 更多