c - 将数组传递给 scanf 函数将不起作用

标签 c arrays printf

我正在做 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 为 0mCode 为空白

最佳答案

变量mCodemPrice是函数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/

相关文章:

c - main{} 括号上的语法错误, "expected while"?

c - C中链表声明的区别

php - 将数组从 url 传递到 mySQL 查询

c++ - 使用 %。在 printf 中

c - 要在输入值的同一行中获取结果,然后由 scanf 获取

c - 为什么 strlen() 不代表我的字符串的实际长度?

c - 我应该如何使用包含数组的结构进行 malloc/realloc?

定义数组时出现 C++ 错误

java - 线程中出现异常 "main"java.lang.ArrayIndexOutOfBoundsException

c - printf 的输出乱序