Scanf 用于两个字符串和一个浮点数
我正在创建一个菜单,需要接受用户的三个输入。
char *fullname;
char *date;
float sal;
printf("\nEnter full name: ");
line92
scanf("%s", &fullname);
printf("\nEnter hire date: ");
Line 94
scanf("%s", &date);
printf("\nEnter salary: ");
Line 96
scanf("%d", &sal);
这些是我收到的错误
Employee.c:92: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char **’
Employee.c:94: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char **’
Employee.c:96: warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘float *’
我可以得到导致这些问题的原因的解释吗?
I am creating a menu that needs to take in an three inputs from the users.
char *fullname;
char *date;
float sal;
printf("\nEnter full name: ");
line92
scanf("%s", &fullname);
printf("\nEnter hire date: ");
Line 94
scanf("%s", &date);
printf("\nEnter salary: ");
Line 96
scanf("%d", &sal);
These are the errors I am recieving
Employee.c:92: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char **’
Employee.c:94: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘char **’
Employee.c:96: warning: format ‘%d’ expects type ‘int *’, but argument 2 has type ‘float *’
Can I get an explanation of what is causing these issues?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有几个问题:
第一:
当您对字符串使用
scanf
时,您不使用&
。所以只需scanf("%s", fullname);
即可。第二:
你的指针没有初始化。请尝试以下操作:
只要您输入最多 255 个字符,此操作就有效。
第三:
您最后一次
scanf
的输入不匹配。当您在格式字符串中指定int
时,您将传入float
。试试这个:There are several problems:
First:
When you use
scanf
for strings you do not use the&
. So justscanf("%s", fullname);
.Second:
Your pointers aren't initialized. Try this instead:
This will work as long as you input at most 255 characters.
Third:
Your typing for the last
scanf
doesn't match. You're passing in afloat
when you've specified anint
in the format string. Try this:这些警告是不言自明的。当您使用
%s
格式说明符调用scanf
时,您需要为其提供一个指向可将字符串复制到的 char 数组的第一个元素的指针。你没有这样做,而是给它一个指向字符的指针的地址。迄今为止也存在同样的问题。另外,请注意,使用上面的代码,如果用户输入长度等于或超过 100 个字符的字符串,就会发生缓冲区溢出。
如果您使用的是 MSVC,则可以使用
scanf_s
函数,该函数要求您输入缓冲区的长度。但是,此功能是 Microsoft 特有的,因此不可移植。对于工资,问题在于格式说明符是
%d
,它用于读取整数,而不是浮点数。使用The warnings are pretty self-explanatory. When you call
scanf
with a%s
format specifier you need to provide it a pointer to the first element of a char array where the string can be copied to. You're not doing that, instead you're giving it the address of a pointer to a char.The same problem exists for date. Also, be aware that using the code above, a buffer overflow will occur if the user enters a string equal to or more than 100 characters in length.
If you're using MSVC you can use the
scanf_s
function instead that requires you to enter the length of the buffer. However, this function is Microsoft specific, hence, non-portable.For salary, the problem is that the format specifier is
%d
, which is used for reading ints, not floats. Use