[英]C string(char array): ignores next scanf because of spaces
say something like this: 说这样的话:
#include <stdio.h>
void main() {
char fname[30];
char lname[30];
printf("Type first name:\n");
scanf("%s", fname);
printf("Type last name:\n");
scanf("%s", lname);
printf("Your name is: %s %s\n", fname, lname);
}
if i type "asdas asdasdasd"
for fname
, it won't ask me to input something for lname
anymore. 如果我为
fname
键入"asdas asdasdasd"
,它将不会要求我输入lname
。 I just want to ask how i could fix this, thank you. 我只是想问一下如何解决这个问题,谢谢。
Putting %s
in a format list makes scanf()
to read characters until a whitespace is found. 将
%s
放在格式列表中会使scanf()
读取字符,直到找到空格 。 Your input string contains a space so the first scanf()
reads asdas
only. 您的输入字符串包含空格,因此第一个
scanf()
仅读取asdas
。 Also scanf()
is considered to be dangerous (think what will happen if you input more then 30 characters), that is why as indicated by others you should use fgets()
. scanf()
被认为是危险的(想想如果输入超过30个字符会发生什么),这就是为什么如其他人所指出你应该使用fgets()
。
Here is how you could do it: 您可以这样做:
#include <stdio.h>
#include <string.h>
int main()
{
char fname[30];
char lname[30];
printf("Type first name:\n");
fgets(fname, 30, stdin);
/* we should trim newline if there is one */
if (fname[strlen(fname) - 1] == '\n') {
fname[strlen(fname) - 1] = '\0';
}
printf("Type last name:\n");
fgets(lname, 20, stdin);
/* again: we should trim newline if there is one */
if (lname[strlen(lname) - 1] == '\n') {
lname[strlen(lname) - 1] = '\0';
}
printf("Your name is: %s %s\n", fname, lname);
return 0;
}
However this piece of code is still not complete. 但是这段代码仍然不完整。 You still should check if
fgets()
has encountered some errors. 你仍然应该检查
fgets()
是否遇到了一些错误。 Read more on fgets()
here . 在这里阅读有关
fgets()
更多信息 。
Use fgets
(or getline
if you are using GNU) to get an entire line instead of until the first whitespace. 使用
fgets
(如果使用GNU则使用getline
)来获取整行,而不是直到第一个空格。
if (fgets(fname, 30, stdin) == NULL) {
// TODO: Read failed: handle this.
}
See it working online: ideone 看到它在线工作: ideone
You could also consider using the function fgets_wrapper
from this answer as it will also remove the new line character for you. 您还可以考虑使用此答案中的函数
fgets_wrapper
,因为它还会为您删除换行符。
change 更改
scanf("%s", fname);
to 至
scanf("%[^\n]%*c", fname);
[^\\n] is accept other than '\\ n' [^ \\ n]接受'\\ n'以外的接受
%*c is ignore one character('\\n') %* c忽略一个字符('\\ n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.