-2
#include <iostream>
using namespace std;

int main() {
   string a = "1234"; //How this string convert in integer number

   system("pause");
   return EXIT_SUCCESS;
}

string a = "1234"; How this convert in integer

Leon
  • 43
  • 1
  • 6

6 Answers6

2

If you have C++11 and onwards, use

int n = std::stoi(a);

(Pre C++11, you could use std::strtol;)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
2

You can use std::stoi() to convert a std::string to an int.

#include <iostream>
#include <string>

int main() {
   std::string a = "1234"; //How this string convert in integer number
   int b = std::stoi(a);
   system("pause");
   return EXIT_SUCCESS;
}
Constantin
  • 8,721
  • 13
  • 75
  • 126
1

You have to use std::stoi:

#include <iostream>
#include <string>

std::string s = "123";
int number= std::stoi(s);
1

You could use boosts lexical cast

#include <boost/lexical_cast.hpp>

std::string str_num = "12345";
int value = 0;
try
{
    value = boost::lexical_cast<int>(str_num);
}
catch(boost::bad_lexical_cast &)
{
    // error with conversion - calling code will deal with
}

This way you can easily modify the code to deal with float or double if your string contains those types of numeric value also

mathematician1975
  • 21,161
  • 6
  • 59
  • 101
0

The C++ Standard has a special function

int stoi(const string& str, size_t *idx = 0, int base = 10);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Probably you can try this

string a = "28787" ;
int myNumber;
istringstream ( a) >> myNumber;

See or you can search for stoi function and see how it can be used. Probably It can work but never try because I dont have the compiler of c++

user2867655
  • 113
  • 8