简体   繁体   English

为什么我的C程序不打印if语句的输出?

[英]Why does my C program not print output from an if statement?

This program ought to output two variables which are in an if statement. 该程序应输出两个位于if语句中的变量。 However it does not but anything printed outside does. 但是,它不会,但是外面打印的任何东西都可以。

#include <stdio.h>
#include <string.h>
char tracks[][80] = {
    "I left my heart in Harvard Med School",
    "Newark, Newark - a wonderful town",
    "Dancing with a Dork",
    "From here to maternity",
    "The girl from Iwo Jima",
};
void find_track(char search_for[])
{
    int i;
    for (i = 0; i < 5; 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;
}

I expected it to output to show the track number and the associated string but it does not. 我希望它输出以显示曲目号和关联的字符串,但事实并非如此。

The fgets function will read a line of text up to a newline, and it will read and store the newline if there is space for it. fgets函数将读取直到换行符的一行文本,并且如果有空格,它将读取并存储换行符 So if for example you enter "here" then search_for will contain "here\\n" . 因此,例如,如果您输入“ here”,那么search_for将包含"here\\n" None of your strings contain a newline so you never find anything. 您的字符串都不包含换行符,因此您什么也找不到。

You'll need to strip the newline from the string that you read in: 您需要从阅读的字符串中删除换行符:

search_for[strcspn(search_for,"\n")]=0; 

The strcspn function returns the number of characters from the start of the string which are not in the given list. strcspn函数从字符串的开头返回不在给定列表中的字符数。 So if your string contains a newline it will return the index of the newline, otherwise it contains the index of the terminating null byte. 因此,如果您的字符串包含换行符,它将返回换行符的索引,否则它将包含终止空字节的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM