Pregunta

For a small portion of my project, I'm supposed to extract data from a text file using cin which my program will know where to cin from based on command line arguments. My issue is how to extract the four pieces of data and ignore the commas. For example, the .txt file will look like the following

(1,2,3,.)
(2,1,3,#)
(3,1,0,.)

In which case I need to extract the 1, the 2, the 3, and the . for the first line. Then move to the second line. When a blank newline is reached than I can exit the getline() scenario through a while loop.

I know I need to use getline() and I was able to extract the data by using the .at() function of the string generated by getline(). I became confused however when a coordinate such as the 1, the 2, or the 3, could be double digits. When this happened, my previous algorithm didn't work so I feel I'm overthinking things and there should be a simpler way to parse this data.

Thanks!

¿Fue útil?

Solución 2

A simple approach is to use sscanf, pass the string you read from cin to it as the first argument

sscanf(s, "(%d,%d,%d,%c)", &a, &b, &c))

If you want to parse the string from scratch, just focus the pattern.

In this case, the pattern is

'(', number, ',', number, ',', number, ',', char, ')'

So you can locate the three commas, then simply extract three numbers from between them.

A more complicated method is regex. But C++ doesn't have native support for that (the Boost library does)

Otros consejos

You can just use the >> operator to a dummy 'char' variable to read in the separators. This assumes you don't care about the 4th token and that it's always a single character:

char ch;
while (ss >> ch)
{
    int a,b,c;
    ss >> a >> ch >> b >> ch >> c >> ch >> ch >> ch;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top