我正在尝试编写一个程序,我必须从键盘输入一个单词,然后它将使用 strcmp() 函数检查文本文件中出现了多少次。这是我的代码。我可以写这个词,但是当我输入输入按钮时,程序就会停止。任何人都可以帮助我弄清楚出了什么问题?
#include "stdafx.h"
#include <string.h>
#include <stdio.h>
int main()
{
char input[20];
char string[20];
int num = 0;
FILE *text;
printf("Enter a word:\n");
scanf_s("%s\n", &input);
fopen_s(&text, "C:\\Users\\USER\\Documents\\Visual Studio 2015\\Projects\\ConsoleApplication8\\text.txt", "r");
if (text == NULL) {
printf("Failed to open file\n");
return (-1);
}
while (!feof(text))
{
fscanf_s(text, "%s", string);
if (!strcmp(string, input));
num++;
}
printf("we found the word %d times\n", num);
return 0;
}`
最佳答案
[从这个“C:\\Users\\USER\\Documents\\Visual Studio 2015\\...
我得出结论,正在使用的编译器是MS-VC]
除了 MarianD 所指出的 feof()
的错误使用之外 在 this answer ,存在以下致命错误:
该行错过了要扫描的缓冲区的大小:
fscanf_s(text, "%s", string);
应该是
fscanf_s(text, "%s", string, (unsigned) sizeof string);
这里同样加 1 问题:
scanf_s("%s\n", &input)
- 传递
输入
,而不是其地址。%s
需要一个char*
(input
衰减到该值)。执行&input
实际上会传递相同的值,但使用错误的类型,即char(*)[20]
,这会调用 UB。 传递其大小:
scanf_s("%s\n", input, (unsigned) sizeof input)
The main difference between the more secure functions (that have the _s suffix) and the other versions is that the more secure functions require the size in characters of each c, C, s, S, and [ type field to be passed as an argument immediately following the variable.
[...]
The size parameter is of type
unsigned
, notsize_t
.
关于c - 如何搜索某个单词在文本文件中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40449725/