kogh
kogh

Reputation: 1015

CString Parsing Carriage Returns

Let's say I have a string that has multiple carriage returns in it, i.e:

394968686
100630382
395950966
335666021

I'm still pretty amateur hour with C++, would anyone be willing to show me how you go about: parsing through each "line" in the string ? So I can do something with it later (add the desired line to a list). I'm guessing using Find("\n") in a loop?

Thanks guys.

Upvotes: 1

Views: 3185

Answers (4)

iammilind
iammilind

Reputation: 70058

If your string is stored in a c-style char* or std::string then you can simply search for \n.

std::string s;
size_t pos = s.find('\n');

You can use string::substr() to get the substring and store it in a list. Pseudo code,

std::string s = " .... ";
for(size_t pos, begin = 0; 
    string::npos != (pos = s.find('\n'));
    begin = ++ pos)
{
  list.push_back(s.substr(begin, pos));
}

Upvotes: 0

Mark Ransom
Mark Ransom

Reputation: 308462

while (!str.IsEmpty())
{
    CString one_line = str.SpanExcluding(_T("\r\n"));
    // do something with one_line
    str = str.Right(str.GetLength() - one_line.GetLength()).TrimLeft(_T("\r\n"));
}

Blank lines will be eliminated with this code, but that's easily corrected if necessary.

Upvotes: 2

Eric Z
Eric Z

Reputation: 14525

You can use stringstream class in C++.

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

int main()
{
   string str = "\
                394968686\
                100630382\
                395950966\
                335666021";
   stringstream ss(str);
   vector<string> v;

   string token;
   // get line by line
   while (ss >> token)
   {
      // insert current line into a std::vector
      v.push_back(token);
      // print out current line
      cout << token << endl;
   }
}

Output of the program above:

394968686
100630382
395950966
335666021

Note that no whitespace will be included in the parsed token, with the use of operator>>. Please refer to comments below.

Upvotes: 0

arviman
arviman

Reputation: 5255

You could try it using stringstream. Notice that you can overload the getline method to use any delimeter you want.

string line;
stringstream ss;
ss << yourstring;
while ( getline(ss, line, '\n') )
{
  cout << line << endl;
}

Alternatively you could use the boost library's tokenizer class.

Upvotes: 1

Related Questions