我正在做 C 编程作业。我面临的问题是用户为 scanf 函数键入的变量始终输出相同的内容。
void Update(char mCode, int mPrice)
{
printf("Enter Code: ");
scanf("%s",&mCode);
printf("Enter Selling Price: ");
scanf("%d",&mPrice);
}
int main(void)
{
....
update(stuff[i].mCode,stuff[i].mPrice);
fp = fopen("readme.txt","a+");
fprintf(fp, "%s %d\n", stuff[i].mCode, &stuff[i].mPrice);
....
return 0;
}
我在 readme.txt 中得到的结果是 mPrice 为 0,mCode 为空白。
最佳答案
变量mCode
和mPrice
是函数Update
中的局部变量。
因此,它们仅在此函数中本地更新。
按如下方式更改:
void Update(char* mCode, int* mPrice)
{
printf("Enter Code: ");
scanf("%s",mCode);
printf("Enter Selling Price: ");
scanf("%d",mPrice);
}
int main(void)
{
....
update(&stuff[i].mCode,&stuff[i].mPrice);
fp = fopen("readme.txt","a+");
fprintf(fp, "%s %d\n", stuff[i].mCode, &stuff[i].mPrice);
....
return 0;
}
关于c - 将数组传递给 scanf 函数将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23583020/