在C中比较用户输入与文本文件和循环
我正在创建一个程序,要求用户输入一个单词。然后将该单词与文本文件中的单词进行比较。如果正确,我希望用户输入另一个单词,该单词应该与文本文件中的下一个单词对应,并且应该循环到文件末尾。我在文件末尾的循环中遇到问题。有人能检查一下我的代码并给我一些建议吗?非常感谢在C中比较用户输入与文本文件和循环,c,loops,file-io,C,Loops,File Io,我正在创建一个程序,要求用户输入一个单词。然后将该单词与文本文件中的单词进行比较。如果正确,我希望用户输入另一个单词,该单词应该与文本文件中的下一个单词对应,并且应该循环到文件末尾。我在文件末尾的循环中遇到问题。有人能检查一下我的代码并给我一些建议吗?非常感谢 #include <stdio.h> #include <string.h> #include <stdlib.h> int main(void) { //Step 1: open file
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
//Step 1: open file and declare variables//
FILE *fp;
fp = fopen("secretwords.txt","r");
char guess[20];
char secret[20];
int i, count;
//Step 2: Check that file opened correctly, terminate if not//
if (fp == NULL)
{
printf("Error reading file\n");
exit (0);
fclose(fp);
}
//Step 3: Create loop to run for each word to run to end of file//
fscanf(fp,"%s", secret);
//Need to create a loop here that will read the text file 20 times,
// each time reading the next word//
for (i=0; i < 3; i++)
{
printf("Please guess the word: \n");
scanf("%s", guess);
if (strcmp(secret,guess)==0)
{
printf("Your guess was correct\n");
return 0; //This return will terminate the program.
// I need to restart loop from here
}
else
{
printf("Your guess was incorrect. Please try again\n");
}
}
return 0;
}
#包括
#包括
#包括
内部主(空)
{
//步骤1:打开文件并声明变量//
文件*fp;
fp=fopen(“secretwords.txt”,“r”);
字符猜测[20];
字符秘密[20];
int i,计数;
//步骤2:检查文件是否正确打开,如果没有,则终止//
如果(fp==NULL)
{
printf(“读取文件时出错”);
出口(0);
fclose(fp);
}
//步骤3:为每个要运行到文件末尾的单词创建要运行的循环//
fscanf(fp,“%s”,机密);
//需要在这里创建一个循环,将文本文件读取20次,
//每次读下一个单词//
对于(i=0;i<3;i++)
{
printf(“请猜猜单词:\n”);
scanf(“%s”,猜测);
if(strcmp(秘密,猜测)==0)
{
printf(“您的猜测是正确的\n”);
返回0;//此返回将终止程序。
//我需要从这里重新启动循环
}
其他的
{
printf(“您的猜测不正确。请重试\n”);
}
}
返回0;
}
- 将从文件读取的
调用移动到返回下一个单词的函数fscanf
- 循环进行用户输入,仅在需要前进到文件中的下一个单词时(当用户输入正确的内容时)调用上述函数
#包括
#包括
#包括
内部主(空)
{
FILE*fp=fopen(“secretwords.txt”、“r”);
如果(fp==NULL)
{
printf(“读取文件时出错”);
返回1;
}
字符猜测[20]={0};
char secret[20]={0};
while(fscanf(fp,“%s”,secret)!=EOF)//如果可以的话,我建议您使用“fscanf_(“%s”,guess);”
{
printf(“请猜猜单词:\n”);
scanf(“%s”,guess);//如果可用,我建议您使用“scanf_s(“%s”,guess);”
if(!strncmp(secret,guess,sizeof(guess)))
{
printf(“您的猜测是正确的。继续…\n”);
}
其他的
{
printf(“您的猜测不正确,再见。\n”);
打破
}
}
fclose(fp);
返回0;
}
我对scanf_s
和fscanf_s
提出了一些建议,如果它们可用,请使用它们。但是,我还是想知道为什么他们还在学校里教坏代码?我不建议使用*scanf*
函数。进一步阅读:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("secretwords.txt", "r");
if (fp == NULL)
{
printf("Error reading file\n");
return 1;
}
char guess[20] = {0};
char secret[20] = {0};
while(fscanf(fp, "%s", secret) != EOF) // i would suggest you use 'fscanf_s("%s", guess);' instead if available
{
printf("Please guess the word: \n");
scanf("%s", guess); // i would suggest you use 'scanf_s("%s", guess);' instead if available
if (!strncmp(secret, guess, sizeof(guess)))
{
printf("Your guess was correct. Continue ...\n");
}
else
{
printf("Your guess was incorrect. Good bye.\n");
break;
}
}
fclose(fp);
return 0;
}