![](/img/trans.png)
[英]Returning const std::string& vs const char* for class member
[英]How to convert const char& to const std::string&?
std::stof()
需要:
float std::stof(const std::wstring &,size_t *)
float std::stof(const std::string &,size_t *)
该函数是将一个由空格分隔的字符串转换为一个包含浮点数的向量。 我尝试使用std::stof()
函数将字符转换为浮点数。 我找不到将const char&
转换为std::stof()
需要的const std::string&
的解决方案。
如何将const char& s
变量转换为const std::string&
变量?
#include<string>
#include <vector>
std::vector<float> parseLine(std::string line)
{
std::vector<float> parsedLine{};
for (int i{}; i < line.size(); i++)
{
if (line[i] != ' ')
{
const char& s = line[i];
float fs = std::stof(s);
parsedLine.push_back(fs);
}
}
return parsedLine;
}
您实际上应该搜索空格分隔符并相应地提取它们之间的子字符串,例如:
#include <string>
#include <vector>
#include <cctype>
std::vector<float> parseLine(const std::string &line)
{
auto is_space = [](unsigned char ch){ return std::isspace(ch); };
std::vector<float> parsedLine;
auto end = line.begin(), start;
while ((start = std::find_if_not(end, line.end(), is_space)) != line.end())
{
end = std::find_if(start, line.end(), is_space);
std::string s(start, end);
float fs = std::stof(s);
parsedLine.push_back(fs);
}
return parsedLine;
}
如果使用std::istringstream
可以大大简化:
#include <string>
#include <vector>
#include <sstream>
std::vector<float> parseLine(const std::string &line)
{
std::vector<float> parsedLine;
std::istringstream iss(line);
// optional:
// iss.exceptions(std::istringstream::failbit);
float fs;
while (iss >> fs){
parsedLine.push_back(fs);
}
return parsedLine;
}
您可以使用std::string
的构造函数
basic_string( size_type count,
CharT ch,
const Allocator& alloc = Allocator() );
将字符转换为std::string
。 引用是const
,因此创建临时对象将起作用。
float fs = std::stof(std::string(1, s));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.