0

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
joelcodes
  • 1
  • 1
  • joelcodes "extremely curious" --> Before `putchar(ans);` add `printf("%d\n", ans);` to see the character code of the `int` you are printing. It is 10 ( a line feed)? – chux - Reinstate Monica Nov 10 '21 at 19:32
  • Side note: For line-based user input, I recommend that you use [`fgets`](https://en.cppreference.com/w/c/io/fgets) instead of `scanf` or `getchar`. See this page for further information: [A beginners' guide away from scanf()](http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html) – Andreas Wenzel Nov 10 '21 at 21:03

1 Answers1

3

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 );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335