user10844703
user10844703

Reputation:

sscanf ignoring spaces in 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'

Is sscanf preprogrammed to ignore whitespaces?
I was expecting :

'test1 ' ' test2'.

Upvotes: 1

Views: 415

Answers (1)

xing
xing

Reputation: 2528

To include the spaces in the scanned strings, the %n specifier, to capture the number of characters processed by the scan, may be the better choice. "%s %n will record the number of characters processed by the first word and the trailing whitespace. %*d%n will scan and discard the integer and record the total number of characters processed to the end of the integer. Then %s%n will skip the whitespace and scan the last word and record the total number of characters processed.
Use strncpy to copy the word and whitespace.

#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;
}

Upvotes: 1

Related Questions