[英]Why is my if statement never evaluated?
I am making a small program in the C90 standard in GCC Ubuntu 10.04 that searches for a word in a line of text and prints out the line if the word is in that line. 我正在GCC Ubuntu 10.04中使用C90标准编写一个小程序,该程序在一行文本中搜索一个单词,如果该行中包含该单词,则将其打印出来。
My source: 我的来源:
#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;
}
My issue is my inner if statement never is true, which I'm assuming means there's something wrong with my strstr function call. 我的问题是我的内部if语句永远都不是真的,我假设这意味着我的strstr函数调用有问题。 Can somebody tell me why that if statement never executes and how to fix it?
有人可以告诉我为什么if语句从不执行以及如何解决它吗? Thanks!
谢谢!
That's because the string you read from the standard input ends with an unnoticed \\n
. 这是因为您从标准输入中读取的字符串以未引起注意的
\\n
结尾。
In this case, searching for a word which is at the end of the line will work, whereas searching for a word in the middle of a line will fail, even if it exists. 在这种情况下,搜索行末尾的单词将起作用,而搜索行中间的单词将失败,即使该单词存在也是如此。
You might want to remove the trailing newline that is copied into word
. 您可能需要删除复制到
word
中的结尾换行符。
One would usually use something such as the following to do this : 人们通常会使用以下内容来做到这一点:
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)
reads an entire line from stream, storing the address of the buffer containing the text into*lineptr
.ssize_t getline(char **lineptr, size_t *n, FILE *stream)
从流中读取整行,并将包含文本的缓冲区地址存储到*lineptr
。 The buffer is null- terminated and includes the newline character, if one was found.如果找到缓冲区,则该缓冲区以null结尾,并包括换行符。
So you need to remove the \\n
from the end of word
before you search it in sentence
. 所以,你需要删除
\\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");
}
you need to remove the '\\n' at the end read by getline, you can add this code after reading input, 您需要在getline读取的末尾删除“ \\ n”,可以在读取输入后添加此代码,
if(word[byteSearch-1]=='\n')
word[byteSearch-1]='\0';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.