Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert char array to single int?

Tags:

c++

char

int

Anyone know how to convert a char array to a single int?

char hello[5]; hello = "12345";  int myNumber = convert_char_to_int(hello); Printf("My number is: %d", myNumber); 
like image 395
IsThisTheEnd Avatar asked May 23 '11 06:05

IsThisTheEnd


People also ask

How do you convert an array to a number?

To convert an array of strings to an array of numbers, call the map() method on the array, and on each iteration, convert the string to a number. The map method will return a new array containing only numbers. Copied! const arrOfStr = ['1', '2', '3']; const arrOfNum = arrOfStr.

How do I turn a char array into a string?

char[] arr = { 'p', 'q', 'r', 's' }; The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);


1 Answers

There are mulitple ways of converting a string to an int.

Solution 1: Using Legacy C functionality

int main() {     //char hello[5];          //hello = "12345";   --->This wont compile      char hello[] = "12345";      Printf("My number is: %d", atoi(hello));       return 0; } 

Solution 2: Using lexical_cast(Most Appropriate & simplest)

int x = boost::lexical_cast<int>("12345");  

Solution 3: Using C++ Streams

std::string hello("123");  std::stringstream str(hello);  int x;   str >> x;   if (!str)  {          // The conversion failed.       }  
like image 161
Alok Save Avatar answered Oct 19 '22 05:10

Alok Save