【发布时间】:2019-11-01 17:46:26
【问题描述】:
如何让我的程序读取文本文件并将文本文件中的单词与我在数组中定义的单词进行比较并打印一条消息。我认为主要问题是 for 循环,因为我不确定它是否正确迭代。这是我的代码:
define MAX_SIZE 1000
int main()
{
FILE * yourfile;
char as_array[MAX_SIZE];
char name[20];
const char * keywords[]={"if", "else", "return", "switch", "case", "default", "for", "do", "while",
"break", "continue", "struct", "typedef", "union", "enum", "sizeof", "int", "float", "double",
"void",
"extern",
"signed", "unsigned", "long", "short", "static", "const", "goto", "auto", "register", "volatile"};
printf("Please write the file you want to open: \n ");
scanf("%s", name);
int number_of_keywords = sizeof(keywords)/sizeof(keywords[0]);
//fopen opens the file; exits with error if the file cannot be opened
if ((yourfile = fopen(name, "r"))== NULL){
printf("Could not open file: %s", name);
exit(1);
}
else printf("Your file has been successfully opened!\n");
while(!feof(yourfile)){
fgets(as_array, MAX_SIZE, yourfile);
printf("%s\n", as_array);
char x = gets(as_array);
for(int i = 0 ; i<number_of_keywords; ++i){
if(keywords[i]== x){
printf("I found word %s\n", keywords[i]);
}
}
return 0;
}
}
【问题讨论】:
-
欢迎来到 Stack Overflow! Why
while(!feof(file))is always wrong -
keywords[i]== x应该是strcmp(keywords[i], x) == 0 -
这条线是干什么用的:
char x = gets(as_array);?那就是从标准输入中读取一行,并用它覆盖as_array。 -
“无法打开文件”是错误消息的典型示例。为什么文件打不开?是权限问题吗?让系统给你一个理由。
if ((yourfile = fopen(name, "r"))== NULL){ perror( name ) ...