目前我正在学习结构和文件,我的任务是创建一个程序来获取字符串输入和数字输入。然后,程序将继续打开一个随机数据库,找到所询问的特定行,并检查字符串是否相等。 文本文件:
Billy
bob
james
peter
mike
kieran
obidiah
scarlett
john
chloe
sarah
leon
david
andrew
shawn
hannah
phoebe
chris
mark
这是我对该程序的(我猜是不正确的)方法:
(它应该如何工作:输入: james ,3.输出:Match)
*FILE *fp;
int main(void)
{
struct store
{
char def[128];
}stock[10];
int count;
char string[64];
printf("Enter the string: ");
scanf("%s",&string);
printf("Enter the line: ");
scanf("%d",&count);
fp=fopen("Names.txt","r");
fscanf(fp,"%127[^\n]%*c", stock[count].def);
if (strcmp(stock[count].def,string)==0)
{
printf("Match");
}
else
{
printf("Nope");
}
fclose(fp);
getch();
}
这符合要求,但程序不会读取文件中的值。 有人知道如何让它工作吗?
我使用 Windows 和 DEV C 编译器。
最佳答案
打字错误:
*FILE *fp;
应该是:
FILE *fp;
scanf
的参数预计是指针,但 string
已经(衰减为)指针。
scanf("%s",&string);
应该是:
scanf("%s",string);
关于C:使用结构比较文件中的 2 个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21430481/