我需要制作一个程序来检查从控制台输入的字符串是否与输入文件中的任何字符串匹配,在我的情况下,只有在我输入了输入文件中最后一行的字符串并且我不知道为什么的情况下,它才起作用
int n;
char c[20];
char broj[20];
FILE* input;
input = fopen("input.txt", "r");
scanf("%s", broj);
while(fgets(c, 200, input) != NULL)
{
if(strcmp(c, broj) == 0)
printf("%s", c);
}
printf("\n");
fclose(input);
return 0;
答案 0 :(得分:1)
正如某些人指出的那样,您正在缓冲区中读取过多内容。
我真的不喜欢在计算缓冲区大小时使用sizeof
运算符,因为结果可能会根据上下文而变化。
void printSizeofTest1(char *test1) {
printf("Size of test1: %d\n", sizeof(test1));
}
int main() {
char *test = NULL;
char test1[10] = { 0 };
char test2 = '\0';
printf("Size of test: %d\n", sizeof(test));
printf("Size of test1: %d\n", sizeof(test1));
printf("Size of test2: %d\n", sizeof(test2));
printSizeofTest1(test1);
return 0;
}
Size of test: 4
Size of test1: 10
Size of test1: 1
Size of test1: 4
在复制和粘贴代码时,您经常会看到这种情况。
相反,最好将指针的长度定义为宏表达式,并始终为有符号字符添加NULL字节填充。永远不要通过sizeof而是通过宏来引用它。这也意味着,如果您需要更改缓冲区的大小,则只需要在一个地方进行更改即可。
关于您的问题。很难看到输入文件,但是,当您使用fgets
时,它将拉回任何新行结束符,这些字符不一定代表您的输入。
#include <stdio.h>
#include <string.h>
#define BUFF_SIZE 20
int main() {
char c[BUFF_SIZE+1] = { 0 },
broj[BUFF_SIZE+1] = { 0 };
FILE *input = fopen("input.txt", "r");
if(NULL != input) { /* <- Test for NULL file pointer */
scanf("%20s", broj); /* <- Provide a width specifier to avoid buffer overflow */
while(fgets(c, BUFF_SIZE, input) != NULL) {
printf("Searching for: %s\nFound: %s\n", broj, c);
if(strcmp(c, broj) == 0)
printf("%s", c);
memset(c, '\0', BUFF_SIZE); /* <- Clear buffer to ensure consistent search results */
}
fclose(input);
input = NULL; /* <- Assign to NULL so that you can check to see if it's closed */
}
printf("\n");
return 0;
}
在此示例中,我从未找到文件的内容,因为我的搜索正在寻找搜索字符串中不存在的换行符。
相反,您应该: