作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个这样的变量:
const std::string& iterations = "30";
我想用它来确定“for”循环的迭代次数:
for ( int i = 0; i < iterations; i++ ) {
// do something
}
该怎么做?我知道我可以像这样转换为字符串:
iterations.c_str();
所以我尝试了 c_int() 但它不起作用:
iterations.c_int();
最佳答案
按优先顺序:
boost::lexical_cast
atoi
std::stringstream
sscanf
请注意 lexical_cast
很简单,可以写在这里:
#include <exception>
#include <sstream>
struct bad_lexical_cast : std::exception {};
template<typename Target, typename Source>
Target lexical_cast(Source arg)
{
std::stringstream interpreter;
Target result;
if(!(interpreter << arg) ||
!(interpreter >> result) ||
!(interpreter >> std::ws).eof())
throw bad_lexical_cast();
return result;
}
它将任何东西转换成任何东西。 (学分:http://www.gotw.ca/publications/mill19.htm)
用法:int iter = lexical_cast<int>(iterations)
关于c++ - 如何将 const std::string& 转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4479961/
我是一名优秀的程序员,十分优秀!