我有一个具有以下模式的文件: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循环:
vector<float> test;
for (float v = 0; test_ss >> v; ) {
test.push_back(v);
test_ss.ignore();
}
RegEx
对于这项任务来说是一种矫枉过正,当你要求substr
矢量时,string
将返回float
。我认为你需要的是使用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