【发布时间】:2012-07-17 11:03:34
【问题描述】:
问题 -> 将固定长度的字符串返回到 std::string*。
目标机器 -> Fedora 11 .
我必须派生一个接受整数值并将固定长度字符串返回到字符串指针的函数;
例如 -> int 值在 0 到 -127 的范围内
所以对于 int 值 0 -> 它应该显示 000
对于值 -9 -> 它应该返回 -009
对于值说 -50 -> 它应该返回 -050
对于值说 -110 -> 它应该返回 -110
所以简而言之,长度在所有情况下都应该相同。
我做了什么:我已经根据如下所示的要求定义了函数。
我需要帮助的地方:我已经导出了一个函数,但我不确定这是否是正确的方法。当我在 Windows 端的独立系统上测试它时,exe 有时会停止工作,但是当我将此功能包含在 Linux 机器上的整个项目中时,它可以完美运行。
/* function(s)to implement fixed Length Rssi */
std::string convertString( const int numberRssi, std::string addedPrecison="" )
{
const std::string delimiter = "-";
stringstream ss;
ss << numberRssi ;
std::string tempString = ss.str();
std::string::size_type found = tempString.find( delimiter );
if( found == std::string::npos )// not found
{
tempString = "000";
}
else
{
tempString = tempString.substr( found+1 );
tempString = "-" +addedPrecison+tempString ;
}
return tempString;
}
std::string stringFixedLenght( const int number )
{
std::string str;
if( (number <= 0) && (number >= -9) )
{
str = convertString( number, "00");
}
else if( (number <= -10) && (number >= -99) )
{
str = convertString( number, "0");
}
else
{
str= convertString(number, "");
}
return str;
}
// somewhere in the project calling the function
ErrorCode A::GetNowString( std::string macAddress, std::string *pString )
{
ErrorCode result = ok;
int lvalue;
//some more code like iopening file and reading file
//..bla
// ..bla
// already got the value in lvalue ;
if( result == ok )
{
*pString = stringFixedLenght( lValue );
}
// some more code
return result;
}
【问题讨论】:
-
代码看起来是正确的,但是哇,你确实有点复杂了:)
-
大家好,谢谢大家的建议,我必须说我确实学到了一些新东西。谢谢 。不过,我只是想知道,如果我的代码没问题并且可行(以某种方式),我还需要更改它吗?
-
@samantha:如果没有人能找到它无效的原因,并且它给出了正确的答案,那么我会说不,你没有有来改变它。但是代码的一个理想属性是它不仅可以工作,而且任何阅读它的人都可以很容易地看到它可以工作。此外,任何想在未来更改它的人都可以轻松地看到它是如何工作的。因此,通常首选更简单的代码。不过,花费数小时将相当简单的代码变成更简单的代码通常是一项糟糕的时间投资,因此您必须判断要改进多少。
标签: c++ string stringstream