从带有空格字符的输入中读取字符串? [英] Reading string from input with space character?
问题描述
我使用的是 Ubuntu,我也使用 Geany 和 CodeBlock 作为我的 IDE.我想要做的是读取一个字符串(如 "Barack Obama"
)并将其放入一个变量中:
I'm using Ubuntu and I'm also using Geany and CodeBlock as my IDE.
What I'm trying to do is reading a string (like "Barack Obama"
) and put it in a variable:
#include <stdio.h>
int main(void)
{
char name[100];
printf("Enter your name: ");
scanf("%s", name);
printf("Your Name is: %s", name);
return 0;
}
输出:
Enter your name: Barack Obama
Your Name is: Barack
如何让程序读取全名?
推荐答案
使用:
fgets (name, 100, stdin);
100
是缓冲区的最大长度.您应该根据需要进行调整.
100
is the max length of the buffer. You should adjust it as per your need.
使用:
scanf ("%[^
]%*c", name);
[]
是扫描集字符.[^
]
告诉当输入 not 时,换行符 ('
'
) 接受输入.然后用 %*c
从输入缓冲区中读取换行符(未读取),*
表示这个读入的输入被丢弃(赋值抑制),因为您不需要它,并且缓冲区中的这个换行符不会对您可能采用的下一个输入造成任何问题.
The []
is the scanset character. [^
]
tells that while the input is not a newline ('
'
) take input. Then with the %*c
it reads the newline character from the input buffer (which is not read), and the *
indicates that this read in input is discarded (assignment suppression), as you do not need it, and this newline in the buffer does not create any problem for next inputs that you might take.
Read here about the scanset and the assignment suppression operators.
注意你也可以使用 gets
但是 ....
Note you can also use gets
but ....
永远不要使用 gets()
.因为在事先不知道数据的情况下无法知道gets() 会读取多少个字符,而且由于gets()
会继续存储超过缓冲区末尾的字符,所以这是极其危险的利用.它已被用来破坏计算机安全.改用 fgets()
.
Never use
gets()
. Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and becausegets()
will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Usefgets()
instead.
这篇关于从带有空格字符的输入中读取字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!