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

+5

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-https://code.sololearn.com/cjSagFdSfw47/?ref=app

c++

6/29/2022 3:28:17 PM

Manav Roy

13 Answers

New Answer

+4

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

+4

Use stoi() function

+3

Based on Мартин's idea https://code.sololearn.com/cdYTxZ4loBIm/?ref=app

+2

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

+2

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

https://code.sololearn.com/chlywr6XU5Ta/?ref=app Check this out

+1

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

+1

Мартин 😑🎵 Hi, Could you please explain your code a bit? I didn't get this line- while(getline(ss,str,delimiter))

+1

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; } }

+1

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

+1

Manav Roy if you don't mind using C functions in C++, strtok supports searching for multiple delimiters to break up a string.

+1

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

0

Brian Thanks:) Will check it out.