當前位置:編程學習大全網 - 行動軟體 - 建立壹個類STR,將壹個任意整數轉換為相應的字符串。例如整數3456轉換為字符串3456

建立壹個類STR,將壹個任意整數轉換為相應的字符串。例如整數3456轉換為字符串3456

怎麽要個類來實現,用個函數不行嗎?還是類中有個字符串的成員用來保存轉換後的字符串?

函數實現的過程我貼出來

#include <iostream>

#include <math.h>

#include <stdlib.h>

using namespace std;

//整數轉換為字符串的函數

char * num_to_str(int ival)

{

char *str = new char[50];

int len =0;

int temp = abs(ival);

char ichar [50];

while(temp!=0)

{ichar[len]=temp%10+48;

len++;

temp/=10;

}

ichar[len]='\0';

int i;

if(ival == 0)

{str[0]='0';

i=1;

}

else if(ival < 0)

{str[0]='-';i=1;len++;}

else i=0;

for(;i<len;i++)

str[i] = ichar[len-i-1];

str[i]='\0';

return str;

}

int main()

{

cout<<num_to_str(0)<<endl;

cout<<num_to_str(12345)<<endl;

cout<<num_to_str(-123)<<endl;

system("pause");

return 0;

}

  • 上一篇:造夢西遊3唐僧配招(要順序!!)
  • 下一篇:為妳而來的相關資訊
  • copyright 2024編程學習大全網