4

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;

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Tomasz Gutkowski
  • 1,388
  • 4
  • 20
  • 28
  • See my solution here : [tokenizing a string of data into a vector of structs?](http://stackoverflow.com/questions/5462022/tokenizing-a-string-of-data-into-a-vector-of-structs/5462907#5462907) – Nawaz Mar 31 '11 at 15:41
  • Personally, I'm partial to my own solution. :) http://stackoverflow.com/questions/3046747/c-stl-selective-iterator/3047106#3047106 – John Dibling Mar 31 '11 at 15:42
  • 1
    BTW, it is Real Madrid, not Real Madryt :) – Andrea Spadaccini Mar 31 '11 at 15:51

4 Answers4

7

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
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
6

If you want to go the C++ way, you can use getline, using ; as the delimiter, as follows.

string s = "Ac milan ; Real Madryt ; 0 ; 2";
string s0, s1;
istringstream iss(s);
getline(iss, s0, ';');
getline(iss, s1, ';');
Didier Trosset
  • 36,376
  • 13
  • 83
  • 122
3

Looks like you have ; as a separator character in the string so you can split the string based on that character. boost::split is useful for this:

string linia = "Ac milan ; Real Madryt ; 0 ; 2";
list<string> splitresults;

boost::split(splitresults, linia, boost::is_any_of(";"));

See Split a string in C++? for other techniques for splitting strings.

Community
  • 1
  • 1
GrahamS
  • 9,980
  • 9
  • 49
  • 63
1

you can also use the std::string::find_first_of() method that allows you to search for character (delimiters) starting from a given position, e.g.

size_t tok_end = linia.find_first_of(";", prev_tok_end+1);
token = linia.substr(prev_tok_end+1, prev_tok_end+1 - tok_end);

However, the boost solution is the most elegant.

davka
  • 13,974
  • 11
  • 61
  • 86