0

I want to print char array (as string) out but it shows an empty string on runtime

Initialization:

    char str1[6]= "Black";
    char str2[7]= "Yellow";

printf statement:

    printf ("%s = %d Bath\n",str1,a);
    printf ("%s = %d Bath\n",str2,a);

expected:

Black = 150 Bath
Yellow = 150 Bath

output

Black = 150 Bath
  = 150 Bath

I tried initializing without size number like char str2[]= "Yellow"; or using a C++ cout to display

raw code:

#include"stdio.h"

#include"conio.h"

main() {
    char str1[6] = "Black";
    char str2[7] = "Yellow";
    char size, E = 'E', S = 'S', M = 'M', L = 'L';
    int receivemoney, change, requiredamount;
    int a = 150;
    int b = 180;
    int c = 200;
    int d = 220;

    while (1) {
        printf("Choose your size? (S,M,L) or E to Exit =", size);
        scanf("%s", & size);

        if (size == E) {
            return 0;

        } else if (size == S) {
            printf("%s = %d Bath\n", str1, a);
            printf("%s = %d Bath\n", str2, a);
            printf("Required amount? =");
            scanf("%d", & requiredamount);
            printf("Receive money ? =");
            scanf("%d", & receivemoney);
            printf("Change ? = ");
            change = ((receivemoney * requiredamount) - 150);
            printf("%d Bath\n", change);
            printf("\n-----------------------\n");

        } else if (size == M) {
            printf("%s = %d Bath\n", str1, b);

        } else if (size == L) {
            printf("%s = %d Bath\n", str1, c);

        }
    }
}
3
  • 1
    C ist not C++ and vice-versa. Do you get any compilation warnings? Fix those first and come back afterwards. Commented Mar 11, 2021 at 15:23
  • 1
    Note: main() is not a valid signature in C afaik. Make it int main(). Commented Mar 11, 2021 at 15:26
  • printf ("Choose your size? (S,M,L) or E to Exit =", size); Your compiler should show some warning about extra parameter size that does not match a format specifier. Commented Mar 11, 2021 at 16:32

2 Answers 2

5
char size ,E= 'E' , S= 'S' , M= 'M', L = 'L';

...

scanf ("%s",&size);

You tell the system to scan a string (due to %s) into a single char (i.e. size).

That is undefined behavior

Use %c for chars.

BTW:

When using scanf you should always check that the return value equals the number of elements you expect to be scan'ed.

So instead of:

scanf("%d",&requiredamount);

you should do:

if (scanf("%d",&requiredamount) != 1)
{
   // Could not scan integer - add error handling
}
Sign up to request clarification or add additional context in comments.

Comments

1

Your problem is here: scanf ("%s",&size);

change into this: scanf ("%c",&size);

It worked for me

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.