How to do this.

How to convert char to int
Like I want to convert char x[]='1' into int y=1.
Because of how ASCII values work, you can take '1' - '0' == 1, if that's what you are asking.
may be i should ask my question with details so here it is......

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>

using namespace std;

int main()
{
           char x[]="29";
           int num;

           // and here should be the piece of code which will convert char data into int
          ?????????????????????????;
          ?????????????????????????;

          //and the value of "char x" should be passed to "int num" without changing it

          cout<<"the value of num is  = "<<num;
          return 0;
}


so the output should look like this.

 
the value of num is = 29


and also i would like to know how to do vice versa
closed account (zb0S216C)
I think you want std::atoi( )[1].

References:
[1]http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

Wazzak
Last edited on
closed account (z05DSL3A)
http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/
thanks that worked but i still have one question (i am a noob)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>

using namespace std;

int main()
{
      char x[256];
      int num=923;
            
       //piece of code
       ??????????;
       //finish

        cout<<"the value of x is = "<<x;
        return 0;
} 


output
 
the value of x is = 923


i just want to convert a numerical char to int data.

i hope i am not missing something about atoi()
You can use a stringstream for something like that, I think.
1
2
3
stringstream ss;
ss<<num;
cout<<ss.str();
To convert chars to int, your use sprintf
1
2
3
char x[256];
int num = 923;
sprintf(x, "%d", num);
Long long time ago I do some testing on some data volume and somewhow C++ stringstream class is very slow in comparison to say sprintf. The effect is only noticeable if say you want to do such conversion a million times perhaps ?
Thank you everyone for help.
Last edited on
Topic archived. No new replies allowed.