c++如何从文本文件中的表中生成多维向量
c++ How to make multidimentional vector from a table in a text file?
我想将下表存储到c++中的多维向量中,这样我就可以通过列名调用值。这是我的桌子:
1 #kjflsj sjflskjf
2 100.00 200.43
3 101.23 198.56
4 102.12 201.87
5 99.67 198.28
6 #sfjslkdjf lsfjls jf jslkfjsij osiioj o
7 100.54 205.98
8 99.87 199.34
9 101.57 202.75
10 103.10 193.50
11 101.78 198.33
12 102.13 204.75
13 #slifjsf ojfosij oiuiso joij
14 104.56 208.34
15 106.14 199.50
16 105.98 200.00
这是我的代码:
16 ifstream myfile;
17 myfile.open (arguments[1]);
18 string line;
19 string sline;
20 vector< vector<double> > values;
21 double x;
24 if (myfile.is_open())
25 {
26 getline(myfile, sline);
27 cout << sline << endl;
28 while (!myfile.eof())
29 {
30 if(line.at(0) != '#')
31 {
32 myfile >> x;
33 values.push_back(vector<double>(x));
34
35 for(int count = 0; count < values.size(); count++)
36 {
37 values.push_back( vector<double>(count) );
38 cout << values.at(0).at(0);
39 }
40 }
41 }
42 }else cout << "The file doesn't exist" << endl;
43 }
我得到的错误:
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at
Aborted (core dumped)
有什么想法吗?
异常的原因可能是:
getline(myfile, sline); // <== reading into "sline"
while (!myfile.eof())
{
if(line.at(0) != '#') // <== checking "line"
{
你正在读一个string
,但查错了!
正确的检查是:
while (getline(myfile, sline)) {
if (sline.at(0) != '#') {
// note that before, for non-commented lines, you
// just dropped sline completely, and went back to the
// file for input. That is wrong, you need to
// parse the line you just got!
std::vector<double> next_row;
std::istringstream iss(sline);
while (iss >> x) {
next_row.push_back(x);
}
// etc.
}
}
一旦修复,就不明显了,但这个循环:
for(int count = 0; count < values.size(); count++)
{
values.push_back( vector<double>(count) );
cout << values.at(0).at(0);
}
如果values
不为空,则实际上是一个无限循环。这是因为在每次迭代中,我们都会在values
中插入一个元素,这会增加它的大小。所以count
和values.size()
每次迭代都会增加一个——你不断地移动目标。这是一个严重的逻辑错误。
相关文章:
- 在 z3 中使用位向量文本
- 遍历对象向量,并找到与从文本文件中提取的对象匹配的变量
- 通过将文本文件读取为字符串/向量来计算加权/未加权 GPA
- 来自文本文件输入 c++ 的向量
- 无法将带有布尔网格的文本文件读取为向量的向量
- 将C++对的向量写入文本文件
- 如何将文本文件行读为向量
- 使用 C++ 中的向量在新行上显示文本文件中的列
- C - 将文本文件读为一串单词,然后将字符串分为向量
- 试图从文本文件中读取向量
- 如何使用两列C 从文本文件中填充向量
- 将文本文件中的行解析为向量
- 使用C 中的向量从文本文件中读取矩阵
- 如何将文本文件的每一行分配给新向量
- 使用getline()从文本文件中读取行,然后将push_back读取到对象的向量中
- C++ 从文本文件数据类型读取为结构,并将数据存储在列表的向量中
- 如何从文本文件中读取数据并将其加载到向量中
- 从文本文件读取到类中的对象向量 - 在另一个 txt 文件中编写
- 如何将字符串从文本文件读取到要搜索的向量中
- c++如何从文本文件中的表中生成多维向量