I don’t know why my string can't save the value
I am writing a C++ function to calculate Hex from Dec, but I don't know why my string can't save the value. Can anybody help me?
string DecToHex(int a){
int i=0,j=0;
string d,c;
while(a!=0)
{
i=a%16;
switch(i)
{
case 10:
d[j]='A';
break;
case 11:
d[j]='B';
break;
case 12:
d[j]='C';
break;
case 13:
d[j]='D';
break;
case 14:
d[j]='E';
break;
case 15:
d[j]='F';
break;
default:
d[j]=48+i;
break;
}
a=a/16;
j++;
}
cout<<"D="<<d;
return d;
}
Change
d[j]='A';
To
d+='A'
And do the same for all the rest.
You are not actually allocating any memory for your string
, so using d[j]
is undefined behavior . You need to use d += ...
or d.push_back(...)
instead.
But even if you fix that error, your code still won't work correctly. It is not outputting any string value at all for a=0
when it should be returning "0"
. And it returns other strings in reverse order. For example, a=16
is returning "01"
instead of "10"
, a=31
is returning "F1"
instead of "1F"
, a=32
is returning "02"
instead of "20"
, etc.
Try something more like this instead:
#include <string>
std::string DecToHex(int a)
{
int i;
std::string d;
d.reserve(sizeof(a)*2);
do
{
i = a % 16;
if ((i >= 10) && (i <= 15))
d.insert(0, 1, 'A'+(i-10));
else
d.insert(0, 1, '0'+i);
a /= 16;
}
while (a != 0);
return d;
}
Or:
#include <string>
#include <algorithm>
std::string DecToHex(int a)
{
int i;
std::string d;
d.reserve(sizeof(a)*2);
do
{
i = a % 16;
if ((i >= 10) && (i <= 15))
d += ('A'+(i-10));
else
d += ('0'+i);
a /= 16;
}
while (a != 0);
std::reverse(d.begin(), d.end());
return d;
}
Or:
#include <string>
#include <sstream>
#include <algorithm>
std::string DecToHex(int a)
{
int i;
std::ostringstream oss;
do
{
i = a % 16;
if ((i >= 10) && (i <= 15))
oss << ('A'+(i-10));
else
oss << ('0'+i);
a /= 16;
}
while (a != 0);
std::string d = oss.str();
std::reverse(d.begin(), d.end());
return d;
}
In any case, your function is not handling negative numbers at all, which requires some extra work (switching to 2s complement representation before then calculating the hex). I'll leave that as an exercise for you to work out.
链接地址: http://www.djcxy.com/p/86322.html上一篇: C ++回文调试
下一篇: 我不知道为什么我的字符串无法保存值