13 Answers
New AnswerSo I've a string, "12|24|64" ,I want to store "12" ,"24"and "64" into an int array, Apparently I've to skip "|". I want to store "12" in 0th index, "24" in 1st index and "64" in 2nd index. How can I do so? I've tried, But instead it's storing sum-https://code.sololearn.com/cjSagFdSfw47/?ref=app
6/29/2022 3:28:17 PM
Manav Roy13 Answers
New Answerstd::stringstream ss("22|23|53"); char delimiter = '|'; std::string str; while(std::getline(ss, str, delimiter)) { std::cout << str << std::endl; }
By default getline(ss, str) would read until new line Default delimiter = '\n' but if you say you want to read until a slash You have to set the delimiter yourself The arguments it takes are input stream, string and delimiter It reads input stream while it doesn't get to the delimiter and stores it in the string It can be used with std::cin and std::ifstream because those are input streams as well
Мартин 😑🎵 Thanks, BTW ,Is it possible to put two delimiters? Like you've put '|' as a delimiter,Is it possible to add one more delimiter?
Мартин 😑🎵 Hi, Could you please explain your code a bit? I didn't get this line- while(getline(ss,str,delimiter))
There is no option like that but you can do something else std::stringstream ss("2-2|24|25"); char del1 = '|', del2 = '-'; std::string str; while(std::getline(ss, str, del1)) { std::stringstream temp(str); while(std::getline(temp, str, del2)) { std::cout << str << std::endl; } }
Manav Roy if you don't mind using C functions in C++, strtok supports searching for multiple delimiters to break up a string.
Here is an example where I used strtok to look for any of three delimiters: https://code.sololearn.com/cZj8IdY69SYu/?ref=app And here is how I did the same task in C++, but without strtok. I used string find instead, after determining which single delimiter to look for: https://code.sololearn.com/c134MzCtfx80/?ref=app
Sololearn Inc.
535 Mission Street, Suite 1591Send us a message