c - 如何搜索某个单词在文本文件中出现的次数

标签 c string io strcmp

我正在尝试编写一个程序,我必须从键盘输入一个单词,然后它将使用 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)
  1. 传递输入,而不是其地址。 %s 需要一个 char*(input 衰减到该值)。执行 &input 实际上会传递相同的值,但使用错误的类型,即 char(*)[20],这会调用 UB。
  2. 传递其大小:

    scanf_s("%s\n", input, (unsigned) sizeof input)
    

来自fscanf_s documentation :

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, not size_t.

关于c - 如何搜索某个单词在文本文件中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40449725/

相关文章:

java - 将 Java NIO 与 IO 输入流读取操作混合

Python readline 和 readlines 行为

c - lwip netconn api - 无法接收来自 SNTP 服务器的应答

c - 为什么在 typedef 中使用指针?

javascript - 替换字符串中的值

java - 如何使用 String.split() 根据 HTML 页面中的标签名称拆分字符串

java - 文件编写器不写下单独的行

c - 如何使用gcc将homepath导入c程序

c - 是否使用 strcpy

c - 如何将文件中的文本写入C中的字符串