【发布时间】: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;
}`
【问题讨论】:
-
从
scanf_s()调用中删除\n。另请参阅:Why is “while ( !feof (file) )” always wrong? -
对于
scanf_s(),同时扫描char或char*,您需要发送第三个参数来指定缓冲区长度,请参见此处:msdn.microsoft.com/en-us/library/w40768et.aspx -
if (!strcmp(string, input));中的分号丢失。 -
scanf 在学习 C 时不适合。像瘟疫一样避免它。
-
@WilliamPursell - 放弃“学习 C 时”,我们 100% 同意。 :-)