I'm writing a program for a beginner c++ class that will read strings from a file and store them into an object which will be in a vector. The file uses ',' as a delimiter and have whitespaces within the strings. I have it working using a bunch of getlines, but I am wondering if there is a way to clean up the code or possibly optimize it.
while getline(ifs,s){
string stream ss(s);
getline(ss,str1,',');
getline(ss,str2,',');
getline(ss,str3,',');
//I take these variables and pushback onto a vector using the object's
//constructor
}
I currently have something like that, but I was wondering if theres a better way to do it. I been looking into overloading extraction operators, but I think I run into the issue of not being able to overload the whitespace delimiter for >>
Generally, you would use a tokenizer for this. boost.tokenizer is great, but for a beginner C++ class, you'll probably want to go with strtok() http://en.cppreference.com/w/cpp/string/byte/strtok
Tokenize your input data using strtok() and then loop over the tokens.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.