954,487 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Converting specified elements of array of char

Hi everyone,

Sorry for the long title! What I want to know is whether it's possible to convert specified elements of array of char to int using some fuction ?
let's say we have char x[10],
x[0] = '9', x[1] = '2'
so I want to have 92 in a single integer variable, is that possible?
or should I copy both elements(extract) to another array of char that consists of 2 elements only then use a function?
what I'm doin right now is subtracting '0' from each element then multiplying it to a variable that has initial value of 1 and gets increased every dealing with each element by *10.


any help?

Mac.Z
Newbie Poster
11 posts since Feb 2007
Reputation Points: 10
Solved Threads: 0
 

type casting

cout << (int)x;

laconstantine
Junior Poster in Training
70 posts since May 2007
Reputation Points: 10
Solved Threads: 1
 

type casting

cout << (int)x;


Yeah, right. :icon_rolleyes:

#include <iostream>
using namespace std;

int main() {
    
    char myString[] = "1234567890";
    cout << (int)myString << endl;
    return 0;
}

/* output

# ./a.out
-1073743883
#

*/


Since you're in C++, I'd recommend stringstreams:

istringstream iss(myString);
int num;
iss >> num;

Don't forget to include <sstream> .

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

The way you are doing it works well, especially if there are more numbers in the array.

And we'd rather have a long title that tells us the topic of the post rather than the usual "help me" or "What's wrong with this urgent" junk titles. So thank you for your long title. :icon_mrgreen:

WaltP
Posting Sage w/ dash of thyme
Moderator
10,505 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You