简体   繁体   English

示例:scanf和char错误

[英]Example: scanf and char errors

I am reading C for Dummies and am doing a example in the book. 我正在阅读C的傻瓜,并在书中做一个例子。 It told me to write it out line by line. 它告诉我逐行写出来。 Then it proceeds through the book even though the code has bugs. 然后,即使代码存在错误,它也会贯穿本书。 Here it is: 这里是:

#include <stdio.h>

int main()
{

char me[20];
printf("What is your name?");
scanf("%s",&me);
printf("Darn glad to meet you. %s!\n".me);

return(0);

}  

According to gcc: 根据gcc:

WHORU.C: In function 'int main()': WHORU.C:8:19: warning: format '%s' expects argument of type 'char*', but argument 2 has type 'char (*)[20]' [-Wformat] WHORU.C:9:43: error: request for member 'me' in '"Darn glad to meet you. %s!\\012"', which is of non-class type 'const char [28]' WHORU.C:在函数'int main()'中:WHORU.C:8:19:警告:格式'%s'期望类型为'char *'的参数,但是参数2的类型为'char(*)[20] '[-Wformat] WHORU.C:9:43:错误:请求''我很高兴见到您。%s!\\ 012''中的成员'me',它是非类类型'const char [28 ]”

Because I am new to C, I can't really point out where I did wrong. 因为我是C语言的新手,所以我无法真正指出我做错了什么。 I do know that this code requires input when it's executed. 我知道该代码在执行时需要输入。 It's kinda like scanner in java. 有点像Java中的扫描器。

Thanks guys. 多谢你们。

scanf("%s",&me);

Should be: 应该:

scanf("%s",me);

scanf() receives a pointer to the variable you passed. scanf()收到指向您传递的变量的指针。 But in C, an array decays to pointer when passed, hence no need of & . 但是在C语言中,数组在传递时会衰减为指针,因此不需要&

Another error is, you have a . 另一个错误是,您有一个. in the printf which should be a , . 在printf的这应该是一个,

printf("Darn glad to meet you. %s!\n".me);

should be: 应该:

printf("Darn glad to meet you. %s!\n",me);

You just use scanf("%s",me); 您只需使用scanf("%s",me); that should solve your problem . 那应该解决你的问题。 In C me[] is equivalent to *me . 在C中, me[]等效于*me

I would hazard a guess that scanf("%s",&me); 我会冒险猜测scanf("%s",&me); should be scanf("%s",&me[0]) or scanf("%s",me) because &me is a pointer to an array of chars, whereas &me[0] is a pointer to a single char at the beginning of an array of chars. 应该为scanf("%s",&me[0])scanf("%s",me)因为&me是指向chars数组的指针,而&me[0]是指向开头的单个char的指针字符数组。 I personally prefer the first way to do it because it seems more logical to me as in "Take the address of the first char in the array me" 我个人更喜欢采用第一种方法,因为对我来说似乎更合逻辑,如“将数组中第一个字符的地址作为我”

Additionally, printf("Darn glad to meet you. %s!\\n".me); 此外, printf("Darn glad to meet you. %s!\\n".me); should probably have a comma, not a period between the string and "me" because me is an argument to the printf function. 应该使用逗号,而不是字符串和“ me”之间的句点,因为me是printf函数的参数。 When you use a period, it's looking for a member on the string "Darn glad to meet you. %s!\\n" called "me" which doesn't exist. 当您使用句点时,它会在字符串“该死的很高兴认识您。%s!\\ n”中寻找一个名为“ me”的成员,该成员不存在。 You would have the same problem in java, so I'm guessing this one is just a typo. 您在Java中会遇到同样的问题,所以我猜这只是一个错字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM