简体   繁体   中英

How can I store and print a character input?

I am familiar with storing and printing characters using getchar(); and putchar();. However, when I use it with my entire code, it does not seem to work. In the command window, it will take the character, but not print it. Thus, I have no idea what the computer is doing. I tried the code for storing and printing a character on its own and it works fine.

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

But as soon as I use it with the entire code, it does not work properly.

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

I'm extremely curious as to why that is and what I need to do to get it work.

Use

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

See the leading space in the format string. It allows to skip white space characters as for example the new line character '\\n' that corresponds to the pressed Enter key.

Or as @chux - Reinstate Monica wrote in his comment instead of declaring the variable ans as having the type char you can declare it with the type unsigned char. For example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM