dtg
dtg

Reputation: 1853

Compiler error attempting to access substring when traversing a string

I am trying in vain to find a way to parse a text file stored in a string object. The format of the string is as follows:

...
1  45
1  46
1  47
2  43
2  44
2  45
...

I am trying to iterate over the whole string, grab each line, and then split the string by the first integer and the second integer for further processing. However, doing something like this doesn't work:

string  fileContents;

string::iterator index;

for(index = fileContents.begin(); index != fileContents.end(); ++index)
{
   cout << (*index);       // this works as expected

   // grab a substring representing one line of the file
   string temp = (*index); // error: trying to assign const char to const char*
}

I am trying to find a way to do this, but so far I haven't had any luck.

Upvotes: 0

Views: 83

Answers (2)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153810

A std::string::iterator identifies a char. A char can possibly be used to form a one element std::string but this probably not what you want. Instead, you can use two iterators to create a std::string, e.g.:

for (std::string::const_iterator begin(s.begin()), it(begin), end(s.end());
     end != (it = std::find(it, end, '\n'); begin = ++it) {
    std::string line(begin, it);
    // do something with the line
}

It may be easier to use the stream functionality with a stream created from you std::string as was pointed out.

Upvotes: 0

hmjd
hmjd

Reputation: 121961

Use istringstreams and std::getline() to obtain the integers from each line:

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::istringstream in("1 45\n1 47\n");
    std::string line;
    while (std::getline(in, line))
    {
        std::istringstream nums(line);
        int i1, i2;
        if (nums >> i1 && nums >> i2)
        {
            std::cout << i1 << ", " << i2 << "\n";
        }
    }
    return 0;
}

See demo at http://ideone.com/mFmynj .

Upvotes: 3

Related Questions