There are a few problems. These three lines all have issues :
scanf("%s", &ans);
ans = toupper(ans);
if(ans == "YES")
For the first line, you are passing the address of a pointer and that is incorrect. You should pass just the pointer. For the second line, toupper operates on just one character so you can't pass the pointer. That means you have to loop through the string and process each character one at a time. In the third line, you can not compare strings like that in C. You have to use
strcmp
to do that. Here are those three lines corrected :
scanf( "%s", ans );
while( * ans ) { * ans = toupper( * ans );
++ans;
}
if( strcmp( array, "YES" ) == 0 )
Your character array is a bit small. What do you think would happen if a user entered eight characters? I would expect bad things so you might want to make it bigger.
Anyway, that should fix those three lines of code.
ETA: merano99 made a good point. Calling
fgets
would be a better option -
cplusplus.com : fgets[
^]. Another option is to use a width specifier in your format string. This is described in the docs -
cplusplus.com : scanf[
^]. For your program, you have a character with 5 characters so you can accept input of 4. A better way to do this is :
#define ARRAY_SIZE 4
char array[ ARRAY_SIZE + 1 ]; char format[ 16 ];
sprintf( format, "%%%ds", ARRAY_SIZE );
scanf( format, ans );
Now you can change the amount of input you accept in just one place. The call to
sprintf
will write a format string that will be "%4s" for
ARRAY_SIZE
of 4. Here is the documentation on sprintf -
cplusplus.com : sprintf[
^]. The triple percents in the format string is a bit unusual. What happens is the first two result in a singe percent and then the third one along with the 'd' handle the integer value and the 's' is a literal value so the result is "%4s". In the call to
scanf
that width specifier will limit input to 4 characters.