Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, how to tokenize this string?

Tags:

c++

scanf

How can I get string like "Ac milan" and "Real Madryt" if they are separated with whitespace?

Here is my attempt:

string linia = "Ac milan ; Real Madryt ; 0 ; 2";
str = new char [linia.size()+1];
strcpy(str, linia.c_str());
sscanf(str, "%s ; %s ; %d ; %d", a, b, &c, &d);

but it doesn't work; I have: a= Ac; b = (null); c=0; d=2;

like image 517
Tomasz Gutkowski Avatar asked Dec 04 '22 09:12

Tomasz Gutkowski


1 Answers

Yes, sscanf can do what you're asking for, using a scanset conversion:

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

int main(){ 

    char a[20], b[20];
    int c=0, d=0;
    std::string linia("Ac milan ; Real Madryt ; 0 ; 2");
    sscanf(linia.c_str(), " %19[^;]; %19[^;] ;%d ;%d", a, b, &c, &d);

    std::cout << a << "\n" << b << "\n" << c << "\n" << d << "\n";
    return 0;
}

The output produced by this is:

Ac milan
Real Madryt
0
2
like image 133
Jerry Coffin Avatar answered Dec 21 '22 23:12

Jerry Coffin