簡體   English   中英

如何存儲和打印字符輸入?

[英]How can I store and print a character input?

我熟悉使用 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);

我非常好奇為什么會這樣,以及我需要做什么才能讓它發揮作用。

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 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM