Reading a mixed data file into a C ++ string

I need to use C ++ to read in text with spaces followed by a numeric value.

For example, data that looks like this:

text1
1.0
text two 
2.1
text2 again
3.1

      

cannot be read with 2 statements "infile >>"

. I had no luck with getline

or. Ultimately I want to populate with struct

these two data items. Any ideas?

0


source to share


4 answers


The IO Standard Library isn't going to do this for you alone, you need some simple parsing of the data to determine where the text ends and the numeric value begins. If you can make some simplifying assumptions (like saying there is exactly one line of text / number per line and minimal error recovery), it wouldn't be too bad to getline () it all into a line and then scan it manually. Otherwise, you're probably better off using a regex or parsing library to handle this rather than reinventing the wheel.



+1


source


Why? You can use getline by providing a space as a line separator. Then align the parts if the next number.



+1


source


If you can be sure that your input is well formed, you can try something like this example:

#include <iostream>
#include <sstream>

int main()
{
    std::istringstream iss("text1 1.0 text two 2.1 text2 again 3.1");

    for ( ;; )
    {
        double x;
        if ( iss >> x )
        {
            std::cout << x << std::endl;
        }
        else
        {
            iss.clear();
            std::string junk;
            if ( !(iss >> junk) )
                break;
        }
    }
}

      

If you need to validate the input (instead of just trying to parse anything that looks like it with a double), you have to write some kind of parser that is not difficult, but boring.

0


source


pseudocode.

This should work. However, it is assumed that you have text / numbers in pairs. You will have to make some attempts to get all printed messages, too.

while( ! eof)
   getline(textbuffer)
   getline(numberbuffer)
   stringlist = tokenize(textbuffer)
   number = atof(numberbuffer)

      

0


source







All Articles