将具有十进制值的矢量字符串转换为整数
convert vector string with decimal value to integer
我有一个带十进制值的矢量字符串,我想把它转换成整数,就像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++的
stof
和stoi
。欺骗非常彻底。"(由评论中的"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
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如何将这个std::字符串转换为std::基本字符串
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 如何在C++中将十六进制字符串转换为文本数据
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何从字符串转换为双精度*
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 如何在C++中将 Python 字符串转换为其转义版本?
- 如何在 C++11 中将标准::字符串转换为标准::u32字符串?
- 如何将整数字符串转换为整数的二维向量?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 将文件复制到自定义位置,存在字符串转换问题
- 将ANSI C字符串转换为UNICODE
- 如何将节点 V8 字符串转换为 C++ 字符串
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将字符串转换为无符号字符数组/字节数组