我正在制作一个程序,它从用户那里获取名称,并用逗号分隔。该程序允许用户在逗号之间放置任意数量的空格。例如:
如果我输入类似的内容
Smith, John
或
Smith,John
我想打印出来
John, Smith
问题是,虽然我的程序无法正确处理上面的以下示例;如果输入类似于
Smith , John
或
Smith ,John.
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LINESIZE 128
int get_last_first(FILE *fp);
int main (void)
{
get_last_first(stdin);
}
/*takes names in the format [LASTNAME],[FIRSTNAME]*/
int get_last_first(FILE *fp)
{
char first[LINESIZE];
char last[LINESIZE];
char line[LINESIZE];
size_t i;
while(1)
{
printf("Enter your last name followed by a comma and your first name\n");
/*if we cant read a line from stdin*/
if(!fgets(line, LINESIZE, fp))
{
clearerr(stdin);
break; /*stop the loop*/
}
/*goes through the line array and checks for non-alphabetic characters*/
for(i = 0; i < strlen(line); i++)
{
if(!isalpha(line[i]))
{
/*if it sees a space hyphen or comma, it continues the program*/
if((isspace(line[i]) || line[i] == ',') || line[i] == '-' )
{
continue;
}
else
{
return -1;
}
}
}
if(sscanf(line, "%s , %s", last, first))
{
printf("%s, %s", first, last);
return 1;
}
return 0;
}
}
是因为我没有正确使用 sscanf 吗?
最佳答案
sscanf()
不进行模式匹配;逗号是完全有效的非空白字符串组件,因此将被 %s
规范吞没。您可以使用诸如 %[^\t,]
之类的内容来匹配直到空格或逗号的一系列字符。
关于c - 如何使用 sscanf 获取名称并按照我想要的方式打印它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6449078/