我是C ++新手,我有一个包含4行3列的文本文件,其中每一行对应一个传感器信号。如何将每一行加载到单独的vector<float>
?
(0.165334,0) (0.166524,-0.0136064) (-0.144899,0.0207161)
(0.205171,0) (0.205084,-0.0139042) (-0.205263,0.0262445)
(0.216684,0) (0.215388,-0.0131107) (-0.193696,0.0251303)
(0.220137,0) (0.218849,-0.0135667) (-0.194153,0.025175)
到目前为止,这是我所拥有的,但是这段代码将数据加载为字符串。我想将最终数据加载为
vector<vector<float>>
吗?vector<vector<string> > input;
ifstream fileFFT(Filename.c_str());
string line;
while(getline(fileFFT, line)){
if(line.empty()){
continue;
}
stringstream row(line);
vector<string> values((istream_iterator<string>(row)),(istream_iterator<string>())); //end
input.push_back(values);
}
最佳答案
您已经有了一半的答案-使用std::getline()
读取每一行,然后使用std::(i)stringstream
处理每一行。
现在,您缺少的是另一半-分析每一行。并且由于您已经知道如何使用std::istream_iterator
,因此我将执行以下操作:
typedef std::pair<float, float> SensorValue;
typedef std::vector<SensorValue> SensorValues;
std::istream& operator>>(std::istream &in, SensorValue &out)
{
float f1, f2;
char ch1, ch2, ch3;
if (in >> ch1 >> f1 >> ch2 >> f2 >> ch3)
{
if ((ch1 == '(') && (ch2 == ',') && (ch3 == ')'))
out = std::make_pair(f1, f2);
else
in.setstate(std::ios_base::failbit);
}
return in;
}
...
std::vector<SensorValues> input;
std::ifstream fileFFT(Filename.c_str());
std::string line;
while (std::getline(fileFFT, line))
{
if (line.empty())
continue;
std::istringstream row(line);
SensorValues values;
std::copy(std::istream_iterator<SensorValue>(row), std::istream_iterator<SensorValue>(), std::back_inserter(values));
input.push_back(values);
}
关于c++ - 如何将文本文件的每一行分配给新 vector ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45970788/