【问题标题】:How to search for the number of times a word appears in a text file如何搜索单词在文本文件中出现的次数
【发布时间】:2016-11-06 13:12:36
【问题描述】:

我正在尝试编写一个程序,我必须从键盘输入一个单词,然后它将使用 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 string io strcmp


【解决方案1】:

[从这个"C:\\Users\\USER\\Documents\\Visual Studio 2015\\ ...我得出结论,使用的编译器是MS-VC]

除了this answerMarianD指出的feof()的错误使用外,还有以下致命错误:

这一行缺少要扫描到的缓冲区的大小:

  fscanf_s(text, "%s", string);

应该是

  fscanf_s(text, "%s", string, (unsigned) sizeof string);

这里同样加一期:

  scanf_s("%s\n", &input)
  1. 传递input,而不是它的地址。 %s 期望 char*input 衰减)。执行&amp;input 实际上会传递相同的值,但使用了错误的类型,即char(*)[20],这会调用UB。
  2. 传递它的大小:

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

来自fscanf_s documentation

更安全的函数(具有 _s 后缀)与其他版本的主要区别在于,更安全的函数需要传递每个 c、C、s、S 和 [ 类型字段的字符大小作为紧跟变量的参数。

[...]

size 参数的类型是unsigned,而不是size_t

【讨论】:

    【解决方案2】:

    改变

    scanf_s("%s\n", &input); 
    

    scanf_s("%s\n", input);
    

    确实输入已经是 char* 并且您正在发送 char (*)[20]

    【讨论】:

    • 不,你错了(尽管它背后的想法通常是正确的)。 input&amp;input 在这种情况下是相同的 - 请参阅 How come an array's address is equal to its value in C?
    • 嗯,这可能是因为你没有使用与我相同的标志进行编译,但如果你尝试使用 -pedantic -Wall 标志,你会收到警告。
    • 这只是 警告(不兼容的指针类型),因为编译器不知道在被调用函数的主体中 使用 this 的任何内容(特别是如果它将执行 指针算术 - 对于input&amp;input,这不同的)。 (=地址)相同,行为在这种情况下也相同,所以你的答案没有机会解决问题。 (对不起你说的不对,但是学习新东西不愉快吗?)
    • @MarianD:值相同但类型错误,因此使用&amp;input会通过传递错误的指针类型来调用UB,即char(*)[20]而不是char*
    • 假设 MS-VC,这个scanf_s("%s\n", input); 是不完整的,不要说错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    相关资源
    最近更新 更多