![](/img/trans.png)
[英]How to convert const char& to const std::string&?
[英]How to cast const std::string& to integer?
我有一個像這樣的變量:
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)
int iters = atoi(str.c_str());
您還可以通過使用字符串流來使用更現代的C ++樣式方法
string s = "1234";
stringstream ss(s);
int i;
ss >> i;
你只需要使用簡單的函數 - atoi(iterations.c_str());
做這個:
istringstream ss(iterators);
int count;
ss >> count;
for ( int i = 0; i < count; i++ ) {
// do something
}
您可以使用以下函數將字符串轉換為數字:
#include <sstream>
#include <string>
#include <ios>
template<class T>
bool str2num( const std::string& s, T *pNumber,
std::ios_base::fmtflags fmtfl = std::ios_base::dec )
{
std::istringstream stm( s.c_str() );
stm.flags( fmtfl );
stm >> (*pNumber);
return stm.fail() == false;
}
要轉換為整數調用,如下所示:
int output;
bool success = str2num( iterations, &output );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.