I am aware of several related questions, such as Parsing a comma-delimited std::string one. However, I have created a code that fits my specific need - to split the string (read from a file) at comma stripping any whitespaces. Later I want to convert these substrings to double and store in std::vector. Not all operations are shown. Here is the code I am giving.
include "stdafx.h" #include<iostream> #include<string> #include<vector> #include<algorithm> int main() { std::string str1 = " 0.2345, 7.9 \n", str2; str1.erase(remove_if(str1.begin(), str1.end(), isspace), str1.end()); //remove whitespaces std::string::size_type pos_begin = { 0 }, pos_end = { 0 }; while (str1.find_first_of(",", pos_end) != std::string::npos) { pos_end = str1.find_first_of(",", pos_begin); str2 = str1.substr(pos_begin, pos_end- pos_begin); std::cout << str2 << std::endl; pos_begin = pos_end+1; } } Output:
0.2345 7.9 So the program goes like this. While loop searches for occurrence of , pos_end will store first occurrence of ,, str2 will be a substring, pos_begin will go to one next to pos_end. First iteration will run fine.
In the next iteration, pos_end will be very large value and I am not sure what pos_end- pos_begin will be. Same goes with pos_begin (though it will be unused). Is making some checks, such as
if (pos_end == std::string::npos) pos_end = str1.length(); a way to go?
The program works on though (g++ -Wall -Wextra prog.cpp -o prog -std=c++11). Is this approach correct?
std::istringstreamandstd::getline()with an appropriate delimiter?