Programming practice -- C/C + + implements the conversion of string and integer respectively

Original link: http://www.cnblogs.com/fengty90/p/3768839.html

C/C + + implements the conversion of string and integer respectively

Premise: itoa and atoi are not used.  

Method 1. A common conversion method of C and C + + is:

1. Convert integer to string: Add '0' and then reverse the order, and the integer plus' 0 'will be implicitly converted to char type number.

2. Convert string to integer: by subtracting '0', the string will be implicitly converted to an int type number.

The code is as follows:

/* C Realize the conversion of numbers to strings and strings to numbers */
#include<stdio.h>

char string[7];	/*Global variable for integer to char*/
char* itoa_test(int num)
{
	int i = 0, j = 0;
	char temp[7];
	while(num)
	{
		temp[i] = num%10 + '0';	/* Implicit conversion of integer plus 0 to char type */
		i++;
		num /= 10;
	}

	i--;
	while(i>=0)	/* Reverse string */
	{
		string[j] = temp[i];
		i--;
		j++;
	}
	string[j] = 0;
	return string;
}

int atoi_test(char* str)
{
	int i = 0, j = 0, sum = 0;
	while(*str != 0)
	{
		sum = sum*10 + ((*str) - '0');	/* String minus 0 will implicitly convert to int type */
		str++;
	}
	return sum;
}

int main()
{
	char str[] = "1314";
	int num = 520;
	int i = atoi_test(str);
	char *s = itoa_test(num);
	printf("atoi: %d\n",i);
	printf("itoa: %s\n",s);
}
The test results are as follows:



Method 2: using string stream in C + +:

A common use of stringstream objects is when you need to implement automatic formatting between multiple data types.

The code is as follows:

#include<iostream>
#include<sstream>
#include<string>
using namespace std;

string test_itoa(int num)
{
	ostringstream ostr;
	ostr << num;
	return ostr.str();
}

int test_atoi(string str)
{
	istringstream istr(str);
	int num;
	istr >> num;
	return num;
}

int main()
{
	string str = "520";
	int num = 1314;
	int i = test_atoi(str);
	string s = test_itoa(num);
	cout<<"atoi: "<<i<<"\nitoa: "<<s<<endl;
}
The operation results are as follows:



Reprinted at: https://www.cnblogs.com/fengty90/p/3768839.html

Posted by Karamja on Sat, 19 Oct 2019 10:40:34 -0700