c - 如何使用 sscanf 获取名称并按照我想要的方式打印它们

标签 c scanf program-entry-point fgetc ansi-c

我正在制作一个程序,它从用户那里获取名称,并用逗号分隔。该程序允许用户在逗号之间放置任意数量的空格。例如:

如果我输入类似的内容

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/

相关文章:

c - 如何从子进程获取返回值给父进程?

c++ - 如何编写确保线程安全的测试用例

java - 构造函数与类的 main 方法中的断言语句背后的推理是什么?

css - 正文和页脚之间不需要的空间

c - Profiling 网络软件/Profiling software with lot of system call waiting

c - Queue中的node_add,只插入前3个作为前中后

c - 如何仅扫描范围内的数据,而不是保存整个数据?

c - 什么是 scanf ("%*s") 和 scanf ("%*d") 格式标识符?

c - 你如何在 C (STDIN) 中扫描重定向的文件?

c++ - 从 C0X32.OBJ 引用的未解析的外部 '_main'