Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - How to convert a string into an integer in C++?
How to convert a string into an integer in C++?
# include & ltiostream & gt

# include & ltcstdio & gt

Use namespace std

int main()

{

int num

char ch[20];

CIN & gt; & gtnum

itoa(num,ch, 10); //Use the function of itoa

cout & lt& ltch & lt& ltendl

}

Method 2:

# include & ltiostream & gt

# include & ltcstdio & gt

Use namespace std

int main()

{

int num

char ch[20];

CIN & gt; & gtnum

sprintf(ch," %d ",num); //Use the function sprintf ()

cout & lt& ltch & lt& ltendl

}

Method 3: (Experience for yourself ...)

# include & ltiostream & gt

# include & ltcstdio & gt

Use namespace std

Long power (int num 1, int num2)

{

Length =1;

for(int I = 1; I<= num2i++)

{

sum = num 1 * sum;

}

Returns the sum;

}

Char* Itoa (long number)

{

for(int I = 0; I & ltnumi++)

{

If(Pow( 10, I) > number)

Break;

}

int h=num/Pow( 10,I- 1);

int * n = new int[I- 1];

for(int j = I- 1; j & gt= 1; j -)

{

num=num%int(Pow( 10,j));

n[j- 1]=num/(Pow( 10,j- 1));

}

char * str = new char[I+ 1];

str[I]= ' \ 0 ';

str[0]= char(h+int(' 0 ');

int m = 1;

for(j = I-2; j & gt=0; j -)

{

num = char(n[j]+int(' 0 ');

str[m]= char(num);

m++;

}

Delete [] n;

Returns a string;

}

int main()

{

int num

char * ch

CIN & gt; & gtnum

ch = Itoa(num); //Use the function of Atoi

cout & lt& ltch & lt& ltendl

Delete ch; //Remember this, it's dynamic.

}