Pregunta

I'm trying to get specific data from a stringstream. I'm reading this data from a file into the stringstream.

f 2/5/6 1/11/6 5/12/6 8/10/6 

Now when I want to read the data into variables, how do I do that? This is the format I want.

stringstream s(line);
string tmpn;
int t[4];
int a, b, c, d, e;
s >>tmpn >>a >>t[0] >>b >>c >>t[1] >>b >>d >>t[2] >>b >>e >>t[3] >>b;

So basically I want the 1st character and then each number in separate values without the slashes.

How can I do this? I tried using sscanf but that was horrible! I'm using C++/CLI.

¿Fue útil?

Solución

If you can guarantee that the input will always be in that format, just replace the slashes with spaces.

replace(line.begin(), line.end(), '/', ' ');

stringstream s(line);
string tmpn;
int t[4];
int a, b, c, d, e;
s >>tmpn >>a >>t[0] >>b >>c >>t[1] >>b >>d >>t[2] >>b >>e >>t[3] >>b;

(replace() is found in the <algorithm> header)

Otherwise, you'll have to manually split it.

Otros consejos

I suggest making a function to read a group:

void read_group(std::stringstream& s, int& a, int& b, int &c)
{
    char temp;
    s >> a;
    s >> temp; // First '/'
    s >> b;
    s >> temp;  // second '/'
    s >> c;
}

If the group and the numbers in the group are related, you may want to create a class for them with a method for extracting from a stringstream.

Using this class that classifies the slash / as whitespace:

struct csv_whitespace
    : std::ctype<char>
{
    static const mask* make_table()
    {
        static std::vector<mask> v(classic_table(), classic_table() + table_size);
        v['/'] |=  space;
        return &v[0];
    }
    csv_whitespace(std::size_t refs = 0) : ctype(make_table(), false, refs) {}
};

You can imbue the input stream with this facet:

iss.imbue(std::locale(iss.getloc(), new csv_whitespace));

And now a slash character will be considered a delimiter. For example:

std::istringstream iss("2/5/6 1/11/6 5/12/6 8/10/6");
iss.imbue(std::locale(iss.getloc(), new csv_whitespace));
int i;

while (iss >> i)
{
    std::cout << i;
}

Output:

2
5
6
1
11
...

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top