将具有十进制值的矢量字符串转换为整数

convert vector string with decimal value to integer

本文关键字:字符串 转换 整数 十进制      更新时间:2023-10-16

我有一个带十进制值的矢量字符串,我想把它转换成整数,就像67.35---->6735atoi不工作?

int n;   
std::vector<std::string> value;   
value= "67.35"

我希望n是6735我知道我可以写一个长代码来做到这一点,但我想知道这是否已经完成了。

这可能是您的解决方案吗?希望这能有所帮助。

#include <boost/lexical_cast.hpp>
#include <string>
int main() 
{    
    std::string sf = "42.2";     
    std::string si = "42";    
    float f = boost::lexical_cast<float>(sf); //f is 42.2    
    int i = boost::lexical_cast<int>(si);  //i is 42 
}

您也可以检查这些:

如何在C++中将数字转换为字符串,反之亦然

如何在C++中将字符串的矢量转换为整数的矢量?


"无论如何,真正的答案是使用C++的stofstoi。欺骗非常彻底。"(由评论中的"Lightness Races in Orbit")

链接:stofstoi

如果只存储一个值,则不需要向量。最简单的方法是:

#include <string> // This needs to be in your headers
float n;
std::string value = "47.65";
n = stof(value) // n is 47.65. Note that stof is needed instead of stoi for floats

如果你需要几个值,你可以这样做:

#include <string>
std::vector<std::string> values;
values.push_back("47.65");
values.push_back("12.34");
//...
std::vector<float> floatValues;
for (int i = 0; i <= values.size(); i++) {
    floatValues.push_back(stof(values[i]));
    // intValues is a vector containing 47.65 and 12.34
}

如果你想在解析字符串之前删除字符串中的小数点,你可以使用以下代码:

#include <algorithm> // This also needs to be in your headers
#include <string>
int n;
std::string value = "47.65";
std::replace(value.begin(), value.end(), '.', '')
n = stoi(value) // n is 4765. This time we're using atoi since we have an int