开发者

2dstrings and strncmp

After i input 10 names ,I have to print all the names that start from A .its not printing anything

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main(void)
{
    int i;
    char names[10][50];
    printf("Enter 10 names:\n");
    for(i=0;i<10;i++)
    {
        printf("Enter name %d\n",i+1);
 开发者_JAVA技巧       gets(names[i]);
    }
    for(i=0;i<10;i++)
    {
        if(!(strncmp(names[i],"A",1)))
        {
        printf("%s",&names[i]);
        }
    }
getch();
}


Aside from a couple of nits (see below), the code looks fine. Personally, I'd change

if(!(strncmp(names[i],"A",1))) 

to

if(names[i][0] == 'A') 

or, even better

if(tolower(names[i][0]) == 'a') // case-insensitive test; make sure ctype.h
                                // has been #included

Nits:

NEVER NEVER NEVER NEVER NEVER use gets(); it is unsafe and creates a security hole that is easily exploited by malware.

Change

gets(names[i]);

to

fgets(names[i], sizeof names[i], stdin);

and pretend you never heard of gets().

Also, make sure that your compiler documentation explicitly says that "void main(void)" is a valid signature; not all compilers support it (the standard signatures for main are either int main(void) or int main(int argc, char **argv)).


Works for me:

Enter 10 name
Enter name 1
jon
Enter name 2
andy
Enter name 3
Andy
Enter name 4
bob
Enter name 5
dave
Enter name 6
fred
Enter name 7
jim
Enter name 8
sarah
Enter name 9
alex
Enter name 10
richard
Andy

The last line there is the matching 'Andy'. Note that this is case sensitive so andy doesn't work whereas Andy does


Your code should work fine. If you're having a problem it might be because you don't flush the output buffer. Adding \n to the printf() line should do it. Or explicitly call fflush() if you prefer.


The code works as expected. Check your input.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜