Sunil Shahi
Sunil Shahi

Reputation: 653

Read data of known format in c++

I had a txt file that contains float numbers separated by space like this:

3.141600 7.54654

4.021560 7.54654

7.54654 4.021560

9.549844 3.141600

and I used the following code to read the data..

int main ()
{

    ifstream file("myFile.txt");

    float x;
    float y;

    while(file >> x >> y)
    std::cout << x << ' ' << y << std::endl;

    system ("pause");
}

That works just fine.....

Now I am given a very strange text file which has some stuff like this:

{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0 Arial;}}

{*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\f0\fs20 0.017453293\tab

2.01623406\par

0.087266463\tab 2.056771249\par

0.191986218\tab 2.045176705\par

0.27925268\tab 1.971733548\par

0.366519143\tab 1.844657601\par

0.453785606\tab 1.669694097\par

0.541052068\tab 1.4539812\par

0.628318531\tab 1.205819241\par

0.715584993\tab 0.934405231\par

0.802851456\tab 0.649540807\par

...... and so on...

I want to read this file and get the x (that appears before \tab) and y (appears before \par) values how can I do that? Notice that there is no space. It is know that \tab and \par appears in all lines of data.

Upvotes: 3

Views: 621

Answers (2)

Grigorii Chudnov
Grigorii Chudnov

Reputation: 3112

You can always use regular expressions, something like:

    std::string pattern("(\\d+.\\d+)\\\\tab[^\\d]+(\\d+.\\d+)\\\\par");
    std::regex r(pattern);

    std::ifstream ifs("input_data.txt");

    std::string data;
    while(getline(ifs, data))
    {
        for (std::sregex_iterator it(data.begin(), data.end(), r), end_it; it != end_it; ++it)
        {
            std::cout << it->str(1) << " " << it->str(2) << std::endl;
        }
    }

(!) If there are line breaks between X and Y values, you might need to read the contents of the file in a string.

EDIT:

A pattern using raw string literals:

std::string pattern(R"((\d+.\d+)\\tab[^\d]+(\d+.\d+)\\par)");

Upvotes: 4

us2012
us2012

Reputation: 16253

Your "strange text file" is in RTF format. You can try to write a parser yourself, but you may well be better off by using a library like http://sourceforge.net/projects/librtf/ .

Even better, ask whoever gave you the data to send it in a proper format. Data for processing in an RTF file is somewhat ridiculous in my humble opinion.

Upvotes: 4

Related Questions