[英]How to get a whole sentence as input using scanf()
I want to get a character and a string and a sentence then write each one of them in a new line.我想得到一个字符、一个字符串和一个句子,然后将它们中的每一个写在一个新行中。 I don't know what is wrong with my code.
我不知道我的代码有什么问题。
#include <stdio.h>
#include <string.h>
int main(){
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
const int MAX_LEN=100;
char ch;
char s[MAX_LEN];
char sentence[MAX_LEN];
scanf ("%c",&ch);
scanf("%s",&s);
scanf("%[^\n]%*c", &sentence);
printf("%c\n",ch);
printf("%s\n", s);
printf("%s\n",sentence);
return 0;
}
Regarding关于
char s[MAX_LEN];
...
scanf("%s",&s);
Use of the &
in this case is wrong.在这种情况下使用
&
是错误的。 s
is created here as an array type, so its symbol by itself already points to the location of the first element, (its address) and has type char *
, which agrees with the "%s"
format specifier used in the scanf
statement. s
在此处创建为数组类型,因此其符号本身已经指向第一个元素的位置(其地址)并且具有类型char *
,这与scanf
语句中使用的"%s"
格式说明符一致。 Prepending s
with the &
changes its type to char(*)[100]
, which is no longer compatible with "%s"
.在
s
前加上&
会将其类型更改为char(*)[100]
,这不再与"%s"
兼容。 Using mismatched format specifiers with scanf()
invokes undefined behavior , which is far worse than your program simply being mal-formed, it is unpredictable.将不匹配的格式说明符与
scanf()
一起使用会调用未定义的行为,这比您的程序只是格式错误要糟糕得多,这是不可预测的。
Note that with warnings turned on (eg, in GCC by compiling with -Wall
) it should result in a message describing all of this.请注意,打开警告(例如,在GCC中通过使用
-Wall
编译)它应该会生成一条描述所有这些的消息。 On my system (not GCC) the following message is issued:在我的系统(不是 GCC)上发出以下消息:
Likewise, when in debug mode with appropriate settings during runtime I see the following assert:同样,在运行时使用适当设置的调试模式时,我会看到以下断言:
"Parameter type mismatch, expecting pointer to char but found pointer to aggregate or user defined." “参数类型不匹配,期望指向 char 的指针,但找到指向聚合或用户定义的指针。”
By the way, when I allowed execution to continue after this warning message the code appeared to work normally, ie it output the content entered into stdin
.顺便说一句,当我在此警告消息后允许继续执行时,代码似乎正常工作,即 output 内容输入
stdin
。 But that is the nature of undefined behavior, anything can happen.但这是未定义行为的本质,任何事情都可能发生。 .
.
The fix here is to simply replace this:这里的解决方法是简单地替换它:
scanf("%s",&s);
With either this:有了这个:
scanf("%s",s); //okay
or this;或这个;
fgets(s, sizeof(s), stdin);//better
s[strcspn(s, "\n")] = 0; // optional, if need to eliminate the newline
either approach works as a replacement for those places in your code where you use an &
on an array.这两种方法都可以替代代码中在数组上使用
&
的地方。
Aside: It is also a good practice to use variable names that self describe themselves.另外:使用自我描述的变量名也是一个好习惯。 Consider using something more descriptive than
s
, eg: char string[MAX_LEN];
考虑使用比
s
更具描述性的东西,例如: char string[MAX_LEN];
or char string_array[MAX_LEN];
或
char string_array[MAX_LEN];
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.