该函数sscanf
尝试从输入缓冲区(在本例中为字符串)读取与您在格式字符串中指定的一样多的项目,并返回已读取项目的数量。
您应该检查缓冲区的“尾部”是否不包含除空格以外的任何符号。
这是一个演示程序。
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *input = "I , am , learning , the , programming , language , C\n";
char a1[42], a2[42], a3[42], a4[42];
int tail = 0;
int result = sscanf( input, "%[^,\n] , %[^,\n] , %[^,\n] , %[^,\n]%n",
a1, a2, a3, a4, &tail );
if ( result == 4 && input[strspn( input + tail, " \t\n" ) + tail] == '\0' )
{
printf( "%s %s %s %s\n", a1, a2, a3, a4 );
}
else
{
puts( "I am sorry but you do not yet know C." );
}
input = "I , am , learning , C \n";
result = sscanf( input, "%[^,\n] , %[^,\n] , %[^,\n] , %[^,\n]%n",
a1, a2, a3, a4, &tail );
if ( result == 4 && input[strspn( input + tail, " \t\n" ) + tail] == '\0' )
{
printf( "%s %s %s %s\n", a1, a2, a3, a4 );
}
else
{
puts( "I am sorry but you do not yet know C." );
}
return 0;
}
它的输出是
I am sorry but you do not yet know C.
I am learning C