首页 > 解决方案 > sscanf忽略C中的空格

问题描述

char s[20] = "test1 16 test2";
char a[20]; char b[20];
sscanf(s, "%s%*d%s", a, b);
printf("'%s' '%s'", a, b); //'test1' 'test2'

sscanf 是否已预先编程为忽略空格?
我期待:

'test1 ' ' test2'.

标签: cstringscanf

解决方案


要在扫描的字符串中包含空格%n,用于捕获扫描处理的字符数的说明符可能是更好的选择。"%s %n将记录第一个单词和尾随空格处理的字符数。%*d%n将扫描并丢弃整数并记录处理的字符总数到整数末尾。然后%s%n将跳过空格并扫描最后一个单词并记录处理的字符总数。
用于strncpy复制单词和空格。

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

#define SIZE 19
//so SIZE can be part of sscanf Format String
#define FS_(x) #x
#define FS(x) FS_(x)


int main ( void) {
    char s[SIZE + 1] = "test1 16 test2";
    char a[SIZE + 1]; char b[SIZE + 1];
    int before = 0;
    int after = 0;
    int stop = 0;
    if ( 2 == sscanf(s, "%"FS(SIZE)"s %n%*d%n%"FS(SIZE)"s%n", a, &before, &after, b, &stop)) {
        if ( before <= SIZE) {
            strncpy ( a, s, before);//copy before number of characters
            a[before] = 0;//terminate
        }
        if ( stop - after <= SIZE) {
            strncpy ( b, &s[after], stop - after);//from index after, copy stop-after characters
            b[stop - after] = 0;//terminate
        }
        printf("'%s' '%s'\n", a, b);
    }
    return 0;
}

推荐阅读