我希望能够扫描一个字符串以这种格式两个空格作为scanf的分隔符
"hello world !!!!"
到
{"hello world", "!!!!"}
这2串超过1个空格隔开。我可以解析这个或至少检测scanf中的两个连续空格吗?
我希望能够扫描一个字符串以这种格式两个空格作为scanf的分隔符
"hello world !!!!"
到
{"hello world", "!!!!"}
这2串超过1个空格隔开。我可以解析这个或至少检测scanf中的两个连续空格吗?
此代码可以帮助你
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char a_buf[5][100] = {0}, sep[3] ,*buf = a_buf[0];
int i = 0;
buf = a_buf[0];
while (scanf("%s%2[ ]",buf,sep) > 1) {
if (strlen(sep)==1)
{
buf += strlen(buf);
*buf++ = ' ';
}
else
buf = a_buf[++i];
}
}
根据该C++参考(http://www.cplusplus.com/reference/cstdio/scanf/)
功能将读取并忽略下一个非空白字符之前遇到的任何空白字符(空格字符包括空格,新行和制表符 - 见isspace为) 。格式字符串中的单个空格验证从流中提取的任何数量的空白字符(包括无)。
我想你应该使用gets:http://www.cplusplus.com/reference/cstdio/gets/然后解析返回的字符串。
编辑。使用fgets(),不会得到()
你应该永远不会*,不管情况如何,使用gets()。使用fgets()代替。 –
'gets'是非常不安全的,因为无法防止缓冲区溢出。至少建议'fgets'。更不用说C11完全取消了“获取”。 – Shahbaz
从你的问题,你似乎不感兴趣的事实,有多个空格,但只是一个方法来解析它们。
不怕! *scanf
中的单个空格字符已忽略全部空格(包括“C”语言环境中的'\n'
,'\r'
,'\t'
和)。所以最简单的形式,你可以这样读:
scanf("%s %s", str1, str2);
当然,你需要错误检查。一种安全的方式是:
char str1[100];
char str2[100];
scanf("%99s", str1);
ungetc('x', stdin);
scanf("%*s");
scanf("%99s", str2);
ungetc('x', stdin);
scanf("%*s");
这是一种通常安全的方式(与您的特定问题无关)。
ungetc
+ scanf("%*s")
忽略字符串的剩余部分(如果有的话)。请注意,在第二个scanf("%99s")
之前不需要任何空格,因为scanf
已经忽略了%s
之前的所有空白(实际上在除%c
和%[
之外的所有%*
之前)。
如果你真的要确保至少有两个空格,而你坚持使用scanf
,你可以这样做:
char str1[100];
char str2[100];
char c;
scanf("%99s", str1);
ungetc('x', stdin);
scanf("%*s");
scanf("%c", &c);
if (c != ' ')
goto exit_not_two_spaces;
scanf("%c", &c);
if (c != ' ')
goto exit_not_two_spaces;
scanf("%99s", str2);
ungetc('x', stdin);
scanf("%*s");
return /* success */
exit_not_two_spaces:
ungetc(c, stdin);
return /* fail */
这些是三个字符串,而不是两个。要读取多个字符而不考虑空格,可以使用fgets()然后解析整个字符串。 –
要检测两个连续的空格,可以使用['strstr()'](http://en.cppreference.com/w/c/string/byte/strstr)函数。 – hmjd