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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章