gpt4 book ai didi

c++ - 如何将 const std::string& 转换为整数?

转载 作者:太空狗 更新时间:2023-10-29 19:42:33 25 4
gpt4 key购买 nike

我有一个这样的变量:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com