Sometimes have a tasks for working with string. Often require changing from string to number, or conversely. In Pascal I'm using "str(n,st);" and "val(st, n, c);", usually. Please, write you methods, how to do it in C++(if you can, specify libraries).
Asked
Active
Viewed 365 times
-3
-
Did you do any research? For `std::string`, you can use `stoi()` – yizzlez Mar 31 '14 at 21:07
-
This question doesn't show any effort to solve the question or even google before asking... – AliciaBytes Mar 31 '14 at 21:10
-
http://en.cppreference.com/w/cpp/header/string look here for a reference on string related methods, the ones you're looking for are under the heading "numeric conversions". – AliciaBytes Mar 31 '14 at 21:11
-
https://stackoverflow.com/q/273908/2157640 https://stackoverflow.com/q/4351371/2157640 https://stackoverflow.com/q/5528053/2157640 https://stackoverflow.com/q/1070497/2157640 – Palec Mar 31 '14 at 22:50
4 Answers
3
In C++ 11 there is a set of functions that convert objects of arithmetic types
to objects of type std::string
string to_string(int val);
string to_string(unsigned val);
string to_string(long val);
string to_string(unsigned long val);
string to_string(long long val);
string to_string(unsigned long long val);
string to_string(float val);
string to_string(double val);
string to_string(long double val);
and a set of functions that convert objects of type std::string
to objects of arithmetic types
:
int stoi(const string& str, size_t *idx = 0, int base = 10);
long stol(const string& str, size_t *idx = 0, int base = 10);
unsigned long stoul(const string& str, size_t *idx = 0, int base = 10);
long long stoll(const string& str, size_t *idx = 0, int base = 10);
unsigned long long stoull(const string& str, size_t *idx = 0, int base = 10);
float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);
There are also some other functions that perform sich conversion that are not listed here by me. For example some of them are C functions that deal with character arrays.

Vlad from Moscow
- 301,070
- 26
- 186
- 335
0
Use std::stoi
std::string example = "21";
int i = std::stoi(example);
Check this answer out for more information c++ parse int from string
0
std::istringstream is("42");
int answer;
is >> answer;
std::ostringstream os;
os << 6*9;
std::string real_answer = os.str();

celtschk
- 19,311
- 3
- 39
- 64
0
Two solutions:
Solution 1:
string strNum = "12345";
int num = atoi(strNum.c_str());
cout<<num<<endl;
Solution 2:
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
string strNum = "12345";
istringstream tempStr(strNum);
int num;
tempStr >> num;
cout<<num<<endl;

derek
- 9,358
- 11
- 53
- 94