This reads one line from a tab delimited file to an array word by word. The problem is that the very last element contains an '\r' and a '\n' (no tab at the end of the line) and the next tab is placed after the first element of the next line.
That's why the last array element contains:
1. the last word of the first line
2. an '\r' character
3. a '\n' character
4. the first element of the next line
If I put the crPos=word.find('\n') line in my code it returns the position of the new line character correctly but crPos=word.find('\r') doesn't return the position of the carriage return.
If you know precisely how many elements are on each line then you can use the normal stream extractor >>, since tab will be treated as another form of white space.
If you don't, then you can use the two-parameter form of getline to read a whole line in one go, then stringstream the contents of that line into your array.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
usingnamespace std;
int main ()
{
string line, word;
vector<string> arr;
stringstream ss( "aa\tbb\tcc\ndd\tee\tff" ); // to simulate the file
while( getline( ss, line ) ) // read a whole line
{
cout << "Line is " << line << endl;
stringstream ssline( line ); // put line in a stringstream
while( ssline >> word ) arr.push_back( word ); // and just extract parts
cout << "Individual words are: ";
for ( string s : arr ) cout << s << " ";
cout << endl;
arr.clear();
}
}
Thanks for your detailed answer. It was also my initial idea to upload my array in two steps you suggested. I thought there was a simpler way to solve this problem.
Anyway I still interested in why the crPos=word.find('\n') line works differently than crPos=word.find('\r')
If I put the crPos=word.find('\n') line in my code it returns the position of the new line character correctly but crPos=word.find('\r') doesn't return the position of the carriage return.
What is the reason of this phenomenon?
If your program is running on a Windows system, a file opened in text mode like this: ifstream file("input.txt"); will automatically have the combination "\r\n" translated to just "\n" during the file input. That means as far as the program is concerned, the '\r' will not be seen, as it is translated out of existence.
You could test that by opening the file in binary mode, ifstream file("input.txt", ios::binary); so that no translation of line-endings takes place. Usually though we want the translation to take place, so that from inside the program the line endings are simply '\n', but outside the program, other applications such as notepad or other text editors will see the expected "\r\n", hence binary mode is usually not used for ordinary text files.