0

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?

4
Contributors
3
Replies
4
Views
10 Years
Discussion Span
Last Post by WaltP
0

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> .

0

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:

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.