C++ 字符串的常规问题

1、把整数转化成字符串,并且不用函数itoa

#include<iostream>
using namespace std;
void itoaAntares();
void atoiAntares();
int main() {
	int num = 12345;
	int j = 0;
	int i = 0;
	char temp[7];
	char str[7];
	while(num) {
		temp[i] = num % 10 + '0';
		i++;
		num = num / 10;
	}
	temp[i] = 0;
	printf("temp=%s\n", temp);
	i = i - 1;
	printf("temp=%d\n", i);

	while (i>=0) {
		str[j] = temp[i];
		j++;
		i--;
	}
	str[j] = 0;
	printf("string=%s\n", str);
	//使得dos界面不闪屏	            
	int in;
	cin >> in;
	return 0;
}

2、把整数转化成字符串,使用函数itoa

void itoaAntares() {
	int number = 12345;
	char str[7];
	_itoa_s(number, str,10);
	printf("integer = %d string = %s\n",number, str);
}

3、字符串转化成整数

void atoiAntares() {
	int sum = 0;
	int i = 0;
	int j = 0;
	char temp[7] = "12345";
	char str[7];
	while (temp[i]) {
		sum = sum * 10 + (temp[i] - '0');
		i++;
	}
	printf("sum=%d\n", sum);
}
4、字符串拷贝函数的实现

char* strcpy_Antares(char* strDest, char* strSrc) {
	if (strDest == NULL || strSrc == NULL) {
		throw "Invalid argument(s)";
	}
	int i;
	char * address = strDest;
	for (i = 0; strSrc[i] != '\0';i++) {
		strDest[i] = strSrc[i];
	}
	strDest[i] = '\0';
	return address;
}
注意:strcpy函数带有返回值,为了实现链式表达式。         


发布了87 篇原创文章 · 获赞 14 · 访问量 14万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章