Gia*_*t45 3 c++ iostream stringstream istream visual-c++
我有一个简单的函数,给定一个字符串str,如果它是一个数字,则返回“true”并覆盖参考输入num。
template <typename T>
bool toNumber(string str, T& num)
{
bool bRet = false;
if(str.length() > 0U)
{
if (str == "0")
{
num = static_cast<T>(0);
bRet = true;
}
else
{
std::stringstream ss;
ss << str;
ss >> num; // if str is not a number op>> it will assign 0 to num
if (num == static_cast<T>(0))
{
bRet = false;
}
else
{
bRet = true;
}
}
}
else
{
bRet = false;
}
return bRet;
}
Run Code Online (Sandbox Code Playgroud)
所以我期望:
int x, y;
toNumber("90", x); // return true and x is 90
toNumber("New York", y); // return false and let y unasigned.
Run Code Online (Sandbox Code Playgroud)
在我的机器上,调试和发布配置都工作正常,但在服务器上,仅使用调试配置,在像toNumber("New York", y)“ss >> num”这样的调用中无法识别这str是一个字符串。
我检查了项目配置,但两台机器都是相同的(服务器是我本地 vs-2015 项目的 svn-checkout )。
我真的不知道如何解决这个问题。谁能帮我这个?
检查输出数字的值operator>>是错误的方法。您应该检查 的stringstream失败状态,例如:
template <typename T>
bool toNumber(string str, T& num)
{
bool bRet = false;
if (str.length() > 0U)
{
if (str == "0")
{
num = static_cast<T>(0);
bRet = true;
}
else
{
std::stringstream ss;
ss << str;
if (ss >> num) // <--
{
bRet = true;
}
else
{
bRet = false;
}
}
}
else
{
bRet = false;
}
return bRet;
}
Run Code Online (Sandbox Code Playgroud)
operator>>返回对输入流的引用,并且流可以bool在布尔上下文中隐式转换,就像if语句一样,其中true表示流处于良好状态,false表示流处于失败状态。
在这种情况下,您可以通过消除冗余分配来进一步大大简化函数,并且bRet冗余输入检查将stringstream已经为您处理,例如:
template <typename T>
bool toNumber(const string &str, T& num)
{
std::istringstream ss(str);
return static_cast<bool>(ss >> num);
// or:
// return !!(ss >> num);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86 次 |
| 最近记录: |