C - 从逗号分隔的浮点线提取字符串
C++ - Extract string from comma separated float line
我有一个带有以下模式的文件: 0.123,0.432,0.123,ABC
我已经成功地将浮点数检索到一个数组中,但是我现在需要找到一种获取最后一个字符串的方法。我的代码如下:
vector<float> test;
for (float v = 0; test_ss >> v; ) {
test.push_back(v);
test_ss.ignore();
}
提示:
- 作为每行元素的数量,它不是一个问题
- 我也不需要特别使用这种结构,我只是在使用它,因为它是我到目前为止发现的最好的。
- 我想要的是,最终要拥有一个带有浮点元素的向量和一个带有最后一个字段的字符串。
一个简单的解决方案是首先使用 std::replace( test_ss.begin(), test_ss.end(), ',', ' ');
替换字符串,然后使用for loop:
vector<float> test;
for (float v = 0; test_ss >> v; ) {
test.push_back(v);
test_ss.ignore();
}
RegEx
将是此任务的过度杀伤,而 substr
将返回 string
,而您询问 float
vector。我认为您需要的是使用ifstream
并将逗号阅读到虚拟char
:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
int main()
{
std::ifstream ifs("file.txt");
std::vector<float> v(3);
std::string s;
char comma; // dummy
if (ifs >> v[0] >> comma >> v[1] >> comma >> v[2] >> comma >> s)
{
for (auto i : v)
std::cout << i << " -> ";
std::cout << s << std::endl;
}
return 0;
}
打印:
0.123 -> 0.432 -> 0.123 -> ABC
相关文章:
- 清除输入缓冲区后未提取字符串流
- 提取字符串中的随机单词
- 提取C++字符串
- 如何提取字符串中的特定值
- 如何提取字符串中的整数?
- 正则表达式:从模式字符串 1.string2'string3 中提取字符串,其中字符串 1 可以包含 '." 字符
- C - 从逗号分隔的浮点线提取字符串
- 如何使用正则表达式提取字符串的不匹配部分
- 处理从 std::istream 中提取字符串的空字符串大小写
- 可视化从文本C++中提取字符串数据
- 如何在C++中有效地提取字符串模式
- 分析文本文件以提取字符串
- C++:从两个符号之间提取字符串
- 提取字符串的一部分并将部分放入字符数组和另一个字符串变量C++
- 如何在c++中提取字符串的一部分
- 使用getline(),然后从用户输入中提取字符串(使用c++)
- 尝试从文本文件中读取列表,然后搜索文本文件,并在c++中提取字符串
- 试图从c++文本文件的单行中提取字符串的一部分
- 从字符数组中提取字符串
- 从JavaScript代码中提取字符串