大哥大姐来帮忙啊!c++ 输入一个整数,转化成16进制的字符串 不用任何函数也可以输出16进制

ps:是转成字符串啊!如输入127,输出“7F” 。下面我编的运行结果居然是符号呢??。。。没思路了。q526779789 用c++ thanx
#include <iostream>
#include <string>

using namespace std;
string convert(int,char*);
const max=16;
int main()
{

int x;

char str[max];
do
{cin>>x;
cout<<convert(x, str)<<endl;}while (x!=0);

return 0;
}

string convert(int num, char *hex)
{
int array[max];
int t=num;

while(t%16)
{
for(int j=0;j<max;j++)
array[j]=t%16;//put mod into array
t=t/16;

}

for(int k=0;k<max;k++)
{ int temp=array[k];
if(temp==10)
{hex[k]='A';}
if(temp==11)
{hex[k]='B';}
if(temp==12)
{hex[k]='C';}
if(temp==13)
{hex[k]='D';}
if(temp==14)
{hex[k]='E';}
if(temp==15)
{hex[k]='F';}

else{
hex[k]=array[k];
}

}

string hexx=hex;
return hexx;

}

/* 由于char[] 数组 做输出只能是数字或字符,比如char a='1' 就会输出1 ;但是 char a=1; 输出 a 就直接输出的 ASCII码 笑脸的符号,要输出1 就要这么写 cout<<a+1-1; 这么写就是将字符转换为 数字,输出结果为1; 但是此题输出的既有数字又有字符 所以就直接全用字符了 代码如下: */

#include<iostream>
using namespace std;
void convert(int num);
const max=16;
int main()
{
int x;
do
{
cout<<"请输入一个数:";
cin>>x;
convert(x);
}while(x!=0);
return 0;
}
void convert(int num)
{
char a[max];
int length=0;
while(num>0)
{
int temp=num%16;//put mod into array
num=num/16;
switch(temp)
{
case 0:a[length]='0';
break;
case 1:a[length]='1';
break;
case 2:a[length]='2';
break;
case 3:a[length]='3';
break;
case 4:a[length]='4';
break;
case 5:a[length]='5';
break;
case 6:a[length]='6';
break;
case 7:a[length]='7';
break;
case 8:a[length]='8';
break;
case 9:a[length]='9';
break;
case 10:a[length]='A';
break;
case 11:a[length]='B';
break;
case 12:a[length]='C';
break;
case 13:a[length]='D';
break;
case 14:a[length]='E';
break;
case 15:a[length]='F';
break;
}
length++;
}
cout<<"转化为16进制数为:";
for(int i=length-1;i>=0;i--)
{
cout<<a[i];
}
cout<<endl;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-08-20
按照你的要求写了个程序,代码如下
#include <iostream>
using namespace std;
void main()
{
int n = 127;
char tmp[10];
sprintf(tmp,"%X",n);//输出7F,"%x"可输出小写7f
cout<<tmp;
}
第2个回答  2010-08-20
不用这么麻烦,c++直接支持数的进制转换
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
using namespace std;
int main()
{
int i;
cin >>i;
ostringstream oss;
oss << hex << i;
char hnum[20];
strcpy(hnum,oss.str().c_str());
cout << hnum << endl;
system("pause");
}
第3个回答  2010-08-20
随手写了一个,看看吧
#include<iostream>
using namespace std;
int main(){
int n;
while(cin >> n){ //输入n
int ans[10],q; //ans数组用来存结果
q = -1;
while(n){
ans[++q] = n%16;
n /= 16;
}
for(int i = q; i >= 0; --i){
if(ans[i] <= 9)cout << ans[i];
else cout << char('A' + ans[i] - 10) ; //10 11 12..15分别对应A B C....F ,类型转换一下即可
}
cout << endl;
}
return 0;
}
第4个回答  2010-08-20
如果只是输出可以这样子。

#include <iostream>
using namespace std;

int main()
{
int a;
cin >> a;
cout << hex << a << endl;
return 0;
}
相似回答