Reputation: 151
void viewonechar(){
char name[25], c[25];
int n;
fp = fopen("Phonebook.txt","r");
printf ("\n\n Enter Character : ");
scanf ("%s",c);
fscanf (fp, "%s %d", name, &n);
while (!feof(fp)){
if ((strcmp(c, name[0])) == 0){ \\ Warning in here
printf (" %s +880%d\n",name, n);
}
fscanf (fp, "%s %d", name, &n);
}
printf ("\n\n");
fclose(fp);
menu();
}
When i compile the code, on the marked line this warning appears, "Passing argument 2 of strcmp makes pointer from integer without a cast". What exactly am i doing wrong?
Upvotes: 0
Views: 4383
Reputation: 121387
There are a number of problems.
Avoid scanf(). See: Why does everyone say not to use scanf? What should I use instead?. Use fgets() instead. Since you are reading just one char, char c[2]
is sufficient (and also will not read in the \n
character).
Always do the error checking for all the standard functions.
Your loop condition is wrong. See: Why is “while ( !feof (file) )” always wrong? You don't need to scan once outside the loop if you fix the loop.
Since you only need to compare the first chars, you can simply use c[0] == name[0]
.
The below code fixes the above issues:
void viewonechar(void)
{
char name[25], c[25];
int n;
FILE fp = fopen("Phonebook.txt","r");
if (!fp) {
perror("fopen");
exit(1);
}
printf ("\n\n Enter Character : ");
if (fgets(c, sizeof c, stdin) == NULL) {
fprintf(stderr, "Input error\n");
exit(1);
}
while (fscanf (fp, "%24s %d", name, &n) == 2) {
if (c[0] == name[0]) {
printf (" %s +880%d\n",name, n);
}
}
printf ("\n\n");
fclose(fp);
menu();
}
Upvotes: 1
Reputation: 5920
int strcmp ( const char * str1, const char * str2 );
Since name
is an array of char
, name[0]
is a char
. strcmp
takes char
pointers as an arguments, so the char
you have supplied is implicitly cast to an int-type and then - to the pointer, which produces an undefined behavior and most likely will lead to the segfault.
Upvotes: 1