Kamil
Kamil

Reputation: 13941

Split string by delimiter by using vectors - how to split by newline?

I have function like this (I found it somewhere, it works with \t separator).

vector<string> delimited_str_to_vector(string& str, string delimiter)
{
  vector<string> retVect;
  size_t pos = 0;

  while(str.substr(pos).find(delimiter) != string::npos)
  {
    retVect.push_back(str.substr(pos, str.substr(pos).find(delimiter))); 
    pos += str.substr(pos).find(delimiter) + delimiter.size(); 
  }

  retVect.push_back(str.substr(pos));

  return retVect;
}

I have problem with splitting string by "\r\n" delimiter. What am I doing wrong?

string data = get_file_contents("csvfile.txt");
vector<string> csvRows = delimited_str_to_vector(data, "\r\n");

I'm sure, that my file uses CRLF for new line.

Upvotes: 1

Views: 804

Answers (2)

perreal
perreal

Reputation: 98088

You can use getline to read the file line by line, which:

Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n' ...) If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it.

Perhaps you are already reading the file through a function that removes line endings.

Upvotes: 2

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

Reputation: 153955

If you open your file in text mode, i.e., you don't mention std::ios_base::binary (or one of it alternate spellings) it is likely that the system specific end of line sequences is replaced by \n characters. That is, even if your source file used \r\n, you may not see this character sequence when reading the file. Add the binary flag when opening the file if you really want to process these sequences.

Upvotes: 1

Related Questions