【发布时间】: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而不是scanf或getchar。有关详细信息,请参阅此页面:A beginners' guide away from scanf()
标签: c char whitespace getchar putchar