简体   繁体   中英

Program keeps on crashing

I don't know why this program doesn't work:

 char syze;
 printf("Please enter your desired size (Choose from S,M,L,XL)\n");
 scanf("%s", &syze);

 if(syze =='S')
 {printf("Available");}


 else if(syze =='M')
     {printf("Available");}
 else if(syze =='L')
     {printf("Available");}
 else if(strcmp(syze,"XL")==0)
     {printf("Available");}
 else
     {printf("Please enter a valid character");}
    return 0;

The problem is in

 scanf("%s", &syze);

in your code, size is of type char and you should be using %c format specifier to scan the input.

If you use %s format specifier to scan the input for a char , essentially you'll be overrunning the allocated memory thereby creating undefined behaviour

Then,

 strcmp(syze,"XL")

is also wrong, as strcmp() needs a ( const ) char * as both the arguments, and you're passing a char as the first one. You can simply make use of the equality operator, == to compare a char .

Finally, a char will never be able to hold "XL" .

Solution: If you need to have "XL" as one of the inputs, you may want to change syze to an array, like

 char syze[3] = {0};

or likewise. In that case, you can keep the scanf() as

scanf("%2s", syze);

and compare your inputs using strcmp() .

You have a problem in strcmp(syze,"XL")==0 . You can't compare a char to a string XL . Use only X for that choice and compare the same as the others if(syze =='X') .

You have another problem in scanf("%s", &syze); . Use %c to scan a char :

 scanf("%c", &syze);`

If you want to keep using the choice "XL", you should declare syze as char syze[3] and compare all choices using strcmp .

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