输入整数(包含正负),将整数转换为字符串 11月13日

来源:互联网 发布:知乎 精华 护肤 编辑:程序博客网 时间:2024/06/05 04:16

 

#include<iostream>

using namespace std;

void inttochar(int n,char *str)

{

 if(str==NULL)

 {

  return;

 }

 int i=0;

 int temp=n<0?-n:n;

 char buf[10]="";

 while(temp)

 {

  

  buf[i++]=temp%10+'0';

  temp=temp/10;

 }

 int len=n<0?++i:i;

 str[i]=0;

 while(1)

 {

  i--;

  if(buf[len-i-1]==0)

   break;

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

 }

 if(i==0)

 {

  str[i]='-';

 }

}

void main()

{

 int x;

 char str[10];

 cout<<"please input an integer:";

 cin>>x;

 cout<<"output:";

 inttochar(x,str);

 cout<<str<<endl;

}