繁体   English   中英

为什么我的if语句从未评估过?

[英]Why is my if statement never evaluated?

我正在GCC Ubuntu 10.04中使用C90标准编写一个小程序,该程序在一行文本中搜索一个单词,如果该行中包含该单词,则将其打印出来。

我的来源:

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

int main(){
    int bytesSearch;
    size_t n = 400;
    char *sentence, *word;
    FILE *pFile;

    pFile = fopen("The War of The Worlds.txt","r");

    if (pFile != NULL) {
        puts ("Please enter a search word:");
        sentence = (char *) malloc (n + 1);
        word = (char *) malloc (n + 1);
        bytesSearch = getline(&word, &n, stdin);
        while ((getline(&sentence, &n, pFile)) != -1) {
            char* strResult = strstr(sentence, word);
            if (strResult) {
                printf("%s\n", sentence);
            }
        }
    }
    free(sentence);
    free(word);
    fclose(pFile);
    return EXIT_SUCCESS;
}

我的问题是我的内部if语句永远都不是真的,我假设这意味着我的strstr函数调用有问题。 有人可以告诉我为什么if语句从不执行以及如何解决它吗? 谢谢!

这是因为您从标准输入中读取的字符串以未引起注意的\\n结尾。

在这种情况下,搜索行末尾的单词起作用,而搜索行中间的单词将失败,即使该单词存在也是如此。

您可能需要删除复制到word中的结尾换行符。

人们通常会使用以下内容来做到这一点:

size_t size = strlen(word);
size_t end = size - 1;
if (size > 0 && word[end] == '\n')
    word[end] = '\0';

手册页显示

ssize_t getline(char **lineptr, size_t *n, FILE *stream)从流中读取整行,并将包含文本的缓冲区地址存储到*lineptr 如果找到缓冲区,则该缓冲区以null结尾,并包括换行符。

所以,你需要删除\\n从结束word ,你在搜索之前sentence

if (pFile != NULL) {
    puts ("Please enter a search word:");
    sentence = (char *) malloc (n + 1);
    word = (char *) malloc (n + 1);
    bytesSearch = getline(&word, &n, stdin);

    if (bytesSearch!=-1) {
        word[strlen(word)-1]='\0'; //removes the '\n' from the word

        while ((getline(&sentence, &n, pFile)) != -1) {
            char* strResult = strstr(sentence, word);
            if (strResult) {
                printf("%s\n", sentence);
            }
        }
    }
    else
        printf("Error taking input!\n");

}

您需要在getline读取的末尾删除“ \\ n”,可以在读取输入后添加此代码,

if(word[byteSearch-1]=='\n')
    word[byteSearch-1]='\0';

暂无
暂无

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

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