I'm testing a small program which basically compares whether 2 input strings are identical (as strcmp does).
I'd want to do something like (users type 2 desired strings on the same line). In this case it should return "The two strings are different"
./a.out foo bar
should I do this to read the user's input strings?
scanf("%s %s", str1, str2);
or
gets(str1); gets(str2);
Here is what I have so far (it seems to stuck in an infinite loop for some reasons)
int mystrcmp(char str1[], char str2[]) {
int i = 0;
while (str1[i] == str2[i]) {
if (str1[i] == '\0' || str2[i] == '\0') break;
i++;
}
if (str1[i] == '\0' && str2[i] == '\0')
return 0;
else
return -1;
}
int main(int argc, char * * argv) {
int cmp;
char str1[1000], str2[1000];
scanf("%s %s", str1, str2);
//gets(str1); gets(str2);
cmp = mystrcmp(str1, str2);
if (cmp == 0)
printf("The two strings are identical.\n");
else
printf("The two strings are different.\n");
return 0;
}
argv.fgetsinstead ofgetsto prevent buffer overflow. What if I wrote two 1001 character words that differed on the last letter? Your program wouldn't be able to handle that.fgetslets you set the number of characters to read to be safe (which should be 1 less than the total size of your buffer).