|
转自:https://zhidao.baidu.com/question/503152122.html
要输入带空格的字符串,要用到一个格式字符:%[] --> 一个字符集。
“%[]”的作用是扫描字符集合:
例如:scanf(“%[^\n]”,str);
具体作用是:如果输入的字符属于方括号内字符串中某个字符,那么就提取该字符;如果一经发现不属于就结束提取。该方法会自动加上一个'\0'到已经提取的字符后面。
#include <stdio.h>
int main()
{
char str[81];
printf("Please input a string:\n");
scanf("%[^\n]",&str);
printf("The string is:\n%s\n",str);
return 0;
}
C语言中scanf()函数提供的“%[]”格式串可以用来进行多个字符的输入,并对结束符进行自定义。 对于%[]还可以用^+任意字符(包括 eof)来结束字符串的输入,如%[^EOF]就是直到有EOF 输入,字符串才中止。
参考代码:
|
1
2
3
4
5
6
7
8
|
#include <stdio.h>
void main()
{
char str[100];
scanf("%[^\n]",str);//直到输入回车键,读取才结束,当然不能超过a定义的大小,否则会出错。此命令与gets(str)效果一样。
printf("%s\n",str);
}
|
|