Reputation: 1
#include<stdio.h>
#include<string.h>
int main()
{
char strg1[];
char strg2[] = "football"
printf("Enter first string: ");
gets(strg1);
if(strcmp(strg1, strg2)==0)
{
printf("\nEqual");
}
else
{
printf("\nNot Equal");
}
return 0;
}
I'm getting a string from the user as input and I want to compare it with a ready-made string I have, whether it's equal or not. When I try with strcmp, they are not equal. When I try with strncmp, for example, user footballABC wrote my string football is still equal because with strncmp it is 8 characters. I've limited it. Is there a solution?
Upvotes: 0
Views: 102
Reputation: 87
You've done following mistakes in your program:
char strg1[];
(It will throw error while compiling).error: definition of variable with array type needs an explicit size or an initializer char strg1[];
gets()
for reading string which can lead to Buffer Overflow
.
while using gets()
you should have been warned by compiler.warning: this program uses gets(), which is unsafe.
Full article why gets() in not safe.
Corrected program:
#include<stdio.h>
#include<string.h>
int main()
{
// char strg1[]; // Error!
char strg1[100]; // Allocate space to Array.
char strg2[] = "football";
printf("Enter first string: ");
scanf("%s",strg1); // Use Scanf() instead of gets().
if(strcmp(strg1, strg2)==0)
{
printf("\nEqual");
}
else
{
printf("\nNot Equal");
}
return 0;
}
Upvotes: 2