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?

Recommended Answers

All 3 Replies

type casting

cout << (int)x;

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

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:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.