Convert string to int and int to string in C++

Shaon Shaonty
1 min readNov 10, 2020

--

collected from google

I think it makes more sense. Empty while loop. It will break that string and at the end print the last word of that string.

while(ss >> newString){ 

}
cout<< newString<< endl;

In the same way, this technique is helpful to convert string to int.

For instance, your main string is same to you 100 . You want to convert 100 , string to int. Now you can apply the previous process to split this string and then —

stringstream _in;
int number;
_in << newString;
_in >> number;

operator << add a string to the string stream object.

operator >> read something from the string stream object.

You can think it like cin cout for remembering. A last don't forget to clear the string stream.

_in.clear();
ss.clear();

A far easier way is to use the string stream like this:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;int main (void) {
stringstream ss;
int foo;
string inp;
while (getline (cin, inp)) {
ss.clear ();
ss.str ("");
ss << inp;
while (ss >> foo) {
cout << foo << endl;
}
}
return 0;
}

Problems to solve:

1. http://uva.onlinejudge.org/external/125/12555.html

2. https://www.urionlinejudge.com.br/judge/en/problems/view/1574

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Shaon Shaonty
Shaon Shaonty

Written by Shaon Shaonty

Data Scientist | Software Engineer | Computer Science Graduate @TU Dresden

No responses yet

Write a response