gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:34:52 24 4
gpt4 key购买 nike

我正在 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 结尾。

在这种情况下,搜索行尾的单词有效,而搜索行中间的单词将失败,即使它存在也是如此。 p>

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

人们通常会使用诸如以下的东西来做到这一点:

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

关于c - 为什么我的 if 语句从未被评估过?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22768872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com