0

I'm new to CPP.

I'm trying to create small console app.

my qustion is, is there a way to change char array to integer...?!

for example:

char myArray[]= "12345678" to int = 12345678 ...?!

tnx

Mohsen Rasouli
  • 352
  • 3
  • 9
  • 22

4 Answers4

6

You don't "change" a type. What you want is to create an object of a certain type, using an object of the other type as input.

Since you are new to C++, you should know that using arrays for strings is not recommended. Use a real string:

std::string myString = "12345678";

Then you have two standard ways to convert the string, depending on which version of C++ you are using. For "old" C++, std::istringstream:

std::istringstream converter(myString);
int number = 0;
converter >> number;
if (!converter) {
    // an error occurred, for example when the string was something like "abc" and
    // could thus not be interpreted as a number
}

In "new" C++ (C++11), you can use std::stoi.

int number = std::stoi(myString);

With error handling:

try {
    int number = std::stoi(myString);
} catch (std::exception const &exc) {
    // an error occurred, for example when the string was something like "abc" and
    // could thus not be interpreted as a number
}
Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
1

Use boost::lexical_cast:

#include <boost/lexical_cast.hpp>

char myArray[] = "12345678";
auto myInteger = boost::lexical_cast<int>(myArray);
  • For someone new to C++ you should probably point him on how to get Boost. – yasouser Mar 09 '14 at 08:57
  • 1
    You Google “boost c++,” click the first result and click “Get Boost.” –  Mar 09 '14 at 09:11
  • @yasouser, do you consider being new to C++ being the same as being new to thinking, using the internet and computers? – Griwes Mar 09 '14 at 10:21
0

The atoi function does exactly this.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

Apart from atoi() with C++11 standard compliant compiler you can use std::stoi().

yasouser
  • 5,113
  • 2
  • 27
  • 41