xcode跳过一个方法并完成

时间:2017-03-30 12:04:42

标签: ios c xcode xcode8

我是Xcode的新编码,但奇怪的是它会跳过一些指令并完成程序而不打印结果。 find_track 方法不会打印歌曲的位置并跳过结束。代码可以构建并且“显然”没有错误(它来自C编码书)。任何熟悉Xcode的人都可以提供帮助吗?

char tracks[][80] = {"my spirit","code songs"};
void find_track(char search_for[]) { 
int i;
for (i = 0; i < 2; i++){
    if (strstr(tracks[i],search_for)){
        printf("Track %i: '%s'\n", i, tracks[i]);
    }
  }
}
int main()
{
char search_for[80];
printf("Search for: \n");
fgets(search_for, 80, stdin);
find_track(search_for); 
return 0;
}
** Program ended with exit code: 0 // exit message from Xcode           

1 个答案:

答案 0 :(得分:1)

fgets在缓冲区中留下换行符(输入密钥)。你可以轻松测试它

int main(void)
{
    char search_for[80];
    printf("Search for: \n");
    fgets(search_for, 80, stdin);
    printf("%s", search_for);

    for (size_t i=0; i<strlen(search_for); i++)
    {
        printf ("%X - %c\n", search_for[i], search_for[i]);
    }

    return 0;
}

来自终端输出的输入my spirit将是

0x6D - m
0x79 - y
0x20 -  
0x73 - s
0x70 - p
0x69 - i
0x72 - r
0x69 - i
0x74 - t
0x0A - 

最终0x0A是&#39; \ n&#39; char:换行。

直接将其传递给find_track函数strstr也会尝试匹配该字符。 如此简单的解决方案是删除该char:

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

char tracks[][80] = { "my spirit", "code songs" };

void find_track(char search_for[])
{
    int i;
    for (i = 0; i < 2; i++)
    {
        if (strstr(tracks[i], search_for) != NULL)
        {
            printf("Track %i: %s\n", i, tracks[i]);
        }
    }
}
int main(void)
{
    char search_for[80];
    printf("Search for: \n");
    fgets(search_for, 80, stdin);
    printf("%s", search_for);

    // Remove newline
    search_for[strlen(search_for)-1] = '\0';

    find_track(search_for);

    return 0;
}