【发布时间】:2014-05-11 05:20:55
【问题描述】:
我正在 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 语句永远不会执行以及如何解决它吗?谢谢!
【问题讨论】:
-
这是一个很好的调试器用例。检查您的环境使用了哪个调试器,并了解如何有效地使用它。
-
请提供最少的输入文件集,并告诉我们您在程序中输入了什么,以便我们重现它。
-
尝试打印
ERRNO找出问题所在。 -
请给你的问题一个更好的标题,以某种方式说明你的技术问题是什么,而不是你如何观察它。
-
@BenjaminC.Huskisson-Snider,您可以立即开始并编辑您的问题,永远不会太晚。
标签: c string file loops pointers