Puriice
Puriice

Reputation: 45

C initialize char array as string but empty when try to printf

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

        }
    }
}

Upvotes: 0

Views: 204

Answers (2)

4386427
4386427

Reputation: 44256

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
}

Upvotes: 5

robbinc91
robbinc91

Reputation: 524

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

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

It worked for me

Upvotes: 1

Related Questions