Im a noob in C and I got this simple code working..

#include <stdio.h>
#include <conio.h>
#include <string.h>

int main ()
{
    char str1[20]="burke",str2[20];
    
    printf("Dog's name?:");
    scanf("%s",str2);
    
    if (strcasecmp(str1, str2)==0){
    printf("Gratz you got it",str2);
    }
    else{
    printf("Wrong Answer!!!");     
    }
    
    getch();
}

My problem is what if instead of "burke" its "burke jr." with space in str1[20] coz somehow i can get it working. >.< been studying C for almost a week now I hope you guys can help me. and give me some tip,hint and advice

#include <stdio.h>
#include <conio.h>
#include <string.h>

int main ()
{
    char str1[20]="burke jr",str2[20];
    
    printf("Dog's name?:");
    scanf("%s",str2);
    
    if (strcasecmp(str1, str2)==0){
    printf("Gratz you got it",str2);
    }
    else{
    printf("Wrong Answer!!!");     
    }
    
    getch();
}

im gettong Wrong Answer

Use fgets() if you want to put spaces in the text. The side affect of fgets() is that it puts '\n' at the end of the string, if it will fit.

printf("Dog's name?:");
fgets(str2, sizeof(str2), stdin);
// now remove the '\n' from the string
if( str2[strlen(str2)-1] == '\n')
   str2[strlen(str2)-1] = '\0';

fgets() is the more robust and generally better input function to use with the user.

In this case, and just as an alternative, a format specifier for scanf() might be used:

scanf("%[^\n]s", str2);
getchar(); //get rid of the newline char

Which tells scanf() to continue taking input until you hit the enter key ('\n' is the newline char you get whenever you hit the enter key).

and after that scanf(), use the getchar() to remove said newline from the keyboard buffer. (Which is THE biggest complaint for noobs in C)

I don't like scanf() for user input BUT it is used in all the classes and books, so ... and this is a very helpful format control for scanf().

>>Which tells scanf() to continue taking input until you hit the enter key

And which is a very good reson not to use it. It's no safer than gets(). Both will let you happly type as many keys as you want, scribbling overflow characters all over the program's memory, causing crashes and sig faults.

This happen because scanf pick up character only till it doesnt see a whitespace('\n' or '\t' or ' '). The rest remained stored in the buffer and is pick up next.
scanf("%[^\n]s", str2);
Writing the above command mean it will pick up character until '\n' is not found. Using fgets is the best option.......i would say go for it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.