如何在 fscanf 中包含逗号

问题描述 投票:0回答:1

我想像这样用 fscanf 扫描“Ryan, Elizabeth 62”行

fscanf(file_ptr, "%s %d", name[i], &age[i]);

但是 fscanf 将逗号作为标志来停止扫描名称。 我怎样才能成功?

谢谢

c function
1个回答
0
投票

考虑使用结构来组织相关信息。
还可以考虑使用

fgets
从文件中读取行。
fscanf
和其他使用
%s
的扫描功能需要限制字符数,以防止向缓冲区写入太多字符。将
#define
字符串化以提供该限制。
格式字符串
" %"FS(LEN_NAME)"[^0-9]%d"
将丢弃前导空格,最多扫描
LEN_NAME
个非数字字符,然后扫描整数。成功扫描将返回 2。名称将包含尾随空格。
另一种方法是使用
strrchr
获取指向字符串中最后一个空格的指针。指针之前的所有内容都是姓名,指针之后的所有内容都是年龄。

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define LEN_NAME 49
// stringify to use in format string
#define FS(x) SFS(x)
#define SFS(x) #x

typedef struct person_s {
    char name[LEN_NAME + 1];
    int age;
} person_t;

int main ( void) {
    char line[LEN_NAME * 2] = "";
    char *space = NULL;
    person_t person = { 0};

    if ( fgets ( line, sizeof line, stdin)) {
        if ( 2 == sscanf ( line, " %"FS(LEN_NAME)"[^0-9]%d", person.name, &person.age)) {
            printf ( "\tname: %s age: %d\n", person.name, person.age);
        }

        if ( ( space = strrchr ( line, ' '))) { // find the last space
            // exclude whitespace preceding last space
            while ( space > line && isspace ( ( unsigned char)*(space - 1))) {
                --space;
            }
            size_t span = space - line;

            if ( span && span <= LEN_NAME) {
                if ( 1 == sscanf ( space, "%d", &person.age)) {
                    strncpy ( person.name, line, span);
                    person.name[span] = 0; // zero terminate
                    printf ( "\tname: %s age: %d\n", person.name, person.age);
                }
            }
        }
    }

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.