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

2
  • atoi, sscanf, stringstream... Commented Mar 9, 2014 at 8:36
  • @yasouser the question is in C++, not C. Mat's comment is right Commented Mar 9, 2014 at 9:57

4 Answers 4

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thats a lot to understand for a guy new to C++
@yasouser: Yes, but what else should he do? He has to learn about strings anyway if he is currently hacking around with char arrays.
1

Use boost::lexical_cast:

#include <boost/lexical_cast.hpp>

char myArray[] = "12345678";
auto myInteger = boost::lexical_cast<int>(myArray);

3 Comments

For someone new to C++ you should probably point him on how to get Boost.
You Google “boost c++,” click the first result and click “Get Boost.”
@yasouser, do you consider being new to C++ being the same as being new to thinking, using the internet and computers?
0

The atoi function does exactly this.

4 Comments

It has undefined behaviour for some inputs and no failure indication though.
@David: atoi cannot distinguish between "0" and "x".
For a very simple question, it's nice to give a very simple answer. Yes, we can go on about subtle nuances.
That's not a nuance. atoi() is a severely broken function, IMO.
0

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

2 Comments

atoi() should be avoided because of error handling. std::to_string() does the opposite of what he wants...
@ChristianHackl: Thanks for pointing out. I meant to point to stoi.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.