I am reading data from a text file and doing this line by line using std::getline . This by default reads the newline character \n . My code is based on this.
However, it turns out that I have to deal with data that can be generated in different environments, i.e. where newline character \r (Mac), \n (Unix) or \r\n (Windows)
Is there a simple fix so that I can do something like
std::getline(data,str,'\r\n','\r','\n');
but first try \r\n and then \r and \n so that it returns a "string" regardless of the environment generated by it?
Or in the general case: is there a way to use std::getline to return a string for any type of commonly used line break / carriage return?
At the moment, all I came up with is
std::vector<int> size(3); for (int i=0;i<3;i++){ data.open(c_string_file_name); switch (i){ case 0: std::getline(data,str,'\r\n');size[0]=str.size();break; case 1: std::getline(data,str,'\r');size[1]=str.size();break; case 2: std::getline(data,str,'\n');size[2]=str.size();break; } data.close(); } int min=std::min_element(size.begin(),size.end()); std::string delim; switch (min){ case 0:delim='\r\n';break; case 1:delim='\r';break; case 2:delim='\n';break; } if ((size[0]==size[1])&&(min==1)){ delim='\r\n'; } //rest of code use std::getline(data,str,delim.c_str());
Based on the assumption that in the presence of line breaks, the corresponding separator will produce the shortest string. It also takes into account the fact that \r and \r\n will have one string of length if it is a delimiter \r\n