How to convert numeric value of a string to int in c++? | Sololearn: Learn to code for FREE!


How to convert numeric value of a string to int in c++?

So 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-


6/29/2022 3:28:17 PM

Manav Roy

13 Answers

New Answer


std::stringstream ss("22|23|53"); char delimiter = '|'; std::string str; while(std::getline(ss, str, delimiter)) { std::cout << str << std::endl; }


Use stoi() function


Based on Мартин's idea


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?

+2 Check this out


🧚Somya🌹 Stoi() function doesn't work with char 😅


Мартин 😑🎵 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; } }


Мартин 😑🎵 Thank you very much bro:)


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: 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:


Brian Thanks:) Will check it out.