gpt4 book ai didi

c - scanf 没有正确存储输入

转载 作者:太空宇宙 更新时间:2023-11-04 02:29:09 24 4
gpt4 key购买 nike

我的代码是这样的:

int nameFull;
printf("What is your name?\n");
scanf("%d\n", &nameFull); \\up until here it seems to work
printf("Hello %d", nameFull);

return 0;

但是无论我输入什么,我每次运行程序时的输出都是“Hello 0”。

有人知道如何解决这个问题吗?

最佳答案

首先 scanf() 不会发出提示,因此在格式字符串中使用任何尾随空白字符并不是一个好主意,例如 \n ,它将导致它读取并丢弃字符,直到下一个非空白字符。

要读一个名字,你可以这样做:

char name[50];
scanf("%49s",name); // 49 to limit the buffer input to prevent buffer overrun , this is a security issue.

您还应该检查 scanf 的返回值以查看操作是否成功。就个人而言,由于存在各种潜在问题,我根本不喜欢使用 scanf()。它仅将程序作者期望的内容作为输入,而不考虑用户可能意外输入的其他输入。查看herehere .还要检查 scanf() man page

更好更安全的方法是使用 fgets() ,

fgets(name,sizeof(name),stdin);

关于c - scanf 没有正确存储输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46386863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com