我在学校里,接到一个作业,要编写一个C程序,该程序从用户处获取输入,然后扫描文件并返回该单词在文件中显示的次数。我觉得我完成了90%,但是由于某种原因,我无法获得while循环。当我运行程序时,它在while循环中崩溃。任何帮助或指导将不胜感激。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>
int main() {
char input[50], file[50], word[50];
int wordcount;
printf("Enter a string to search for\n");
scanf("%s", input);
printf("Enter a file location to open\n");
scanf("%s", file);
FILE * fp;
fp = fopen("%s", "r", file);
while (fscanf(fp, "%s", word) != EOF) {
if (strcmp(word, input)) {
printf("found the word %s\n", input);
wordcount++;
}
}
printf("The world %s shows up %d times\n", input, wordcount);
system("pause");
}
最佳答案
您有2个问题:
fp = fopen("%s", "r", file);
是不正确的,
fopen
仅需要两个参数,而不是三个。正确的版本是
fp = fopen(file, "r");
请注意,C语言没有任何功能可让您构造
来自像这样的变量的字符串
"%s", variable
1这仅适用于功能例如
printf
,它读取格式并根据您可以查看here的规则。
第二个问题是:
if (strcmp(word, input))
strcmp
用于比较两个字符串,但是当字符串比较时返回0等于,否则为非零。所以正确的检查应该是
if(strcmp(word, input) == 0)
{
printf("found the word %s\n", input);
wordcount++;
}
最后一件事:使用
scanf
读取字符串时,应限制数量读取的字符数,否则您将溢出缓冲区,从而产生
可能导致段错误的不确定行为。
input
是char[50]
,因此最多可以容纳49个字符,更好scanf
呼叫应为scanf("%49s", input);
这样做可以确保不要写超出数组范围的内容。
脚注
1字符串
"%s"
在C语言中没有任何实际含义其他字符串,它通常是一个字符序列,以
'\0'
终止字符。该字符串的内存布局为+---+---+----+
| % | s | \0 |
+---+---+----+
printf
系列函数给出了某些字符序列(以
%
开头的)定义明确。它们用于确定应变量的类型在打印以及其他格式选项时使用。有关更多信息,请参见the
printf
documentation。你必须但是请记住,这种类型的构造仅适用于
printf
,因为printf
被设计为以这种方式工作。如果需要使用其他变量的值构造字符串,则需要
具有足够空间的数组并使用类似
sprintf
的函数。对于例:
const char *base = "records";
int series = 8;
char fn[100];
sprintf(fn, "%s%d.dat", base, series);
// now fn has the string "records8.dat"
FILE *fp = fopen(fn, "r");
...
但是在您的情况下,这是不必要的,因为整个文件名已经
存储在变量
file
中,因此不能基于file
构造新的字符串需要。
关于c - 编写一个程序,将用户的输入与文件中的单词进行比较,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49311404/