比较C中的String和每个元素是指向字符串的指针

时间:2014-10-03 23:04:43

标签: c string strcmp

对于我下面的代码,如果我键入四号并且将,ed,bob,bill,我希望输入为ryan。基本上输出是不是名字中的输入之一。它应该是唯一的名字。

但是我的代码没有得到任何输出。它确实编译。 任何人都可以帮我解决这个问题吗?非常感谢帮助。提前致谢。

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

 int main(void)

{
int input_num=0;
int isWill = 0;
int isBob  = 0;
int isBill = 0;
int isRyan = 0;
int isEd = 0;
int i=0;

scanf("%d", input_num);
printf("%d", input_num);

for(i;i<input_num;i++)
{
    char tmp[1000000];
    scanf("%s", tmp);

    if( strcmp( tmp, "Will" ) == 0 )
        isWill = 1;
    else if( strcmp( tmp, "Bob" ) == 0 )
        isBob = 1;
    else if( strcmp( tmp, "Bill" ) == 0 )
        isBill = 1;
    else if( strcmp( tmp, "Ryan" ) == 0 )
        isRyan = 1;
    else if( strcmp( tmp, "Ed" ) == 0 )
        isEd = 1;

}
//end of input

char *colors[5];

colors[0] = "Will";
    printf("Will\n");
colors[1] = "Bob";
    printf("Bob\n");
colors[2] = "Bill";
    printf("Bill\n");
colors[3] = "Ryan";
    printf("Ryan\n");
colors[4] = "Ed";
    printf("Ed\n");

return 0;

}

2 个答案:

答案 0 :(得分:0)

一些错误是:
scanf("%d", input_num);:它应该是scanf("%d", &input_num);
不是错误,而是无用的:for(i;i<input_num;i++):为什么有i:它应该是for(;i<input_num;i++)

如果我理解你的问题你想要输出未写的名字,那么循环后的所有内容都是错误的 你应该看到is_something中哪一个等于0并打印出来

答案 1 :(得分:0)

这是一个解决方案。

如果我输入1和Sally,我会得到所有5个人,对吗?

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

int
main (void)
{
    int input_num = 0;
    enum { WILL = 1, BOB = 2, BILL = 4, RYAN = 8, ED = 16 };
    int all = WILL + BOB + BILL + RYAN + ED;

    scanf ("%d", &input_num);

    for (int i = 0; i < input_num; i++) {
        char tmp[20];

        scanf ("%s", tmp);

        if (strcmp (tmp, "Will") == 0)
            all -= WILL;
        else if (strcmp (tmp, "Bob") == 0)
            all -= BOB;
        else if (strcmp (tmp, "Bill") == 0)
            all -= BILL;
        else if (strcmp (tmp, "Ryan") == 0)
            all -= RYAN;
        else if (strcmp (tmp, "Ed") == 0)
            all -= ED;
    }

    if (all & WILL) {
        puts ("Will");
    }

    if (all & BOB) {
        puts ("Bob");
    }

    if (all & BILL) {
        puts ("Bill");
    }

    if (all & RYAN) {
        puts ("Ryan");
    }

    if (all & ED) {
        puts ("Ed");
    }

    return 0;
}