【发布时间】:2017-03-23 17:09:10
【问题描述】:
我有一个数据文件“records.txt”,格式如下:
2 100 119 107 89 125 112 121 99 124 126 123 103 128 77 85 86 115 66 117 106 75 74 76 96 93 73 109 127 110 67 65 80
1 8 5 23 19 2 36 13 16 24 59 15 22 48 49 57 46 47 27 51 6 30 7 31 41 17 43 53 34 37 42 61 54
2 70 122 81 83 72 82 105 88 95 108 94 114 98 102 71 104 68 113 78 120 84 97 92 116 101 90 111 91 69 118 87 79
1 35 14 12 52 58 56 38 45 26 32 39 9 21 11 40 55 50 44 18 20 63 10 60 28 1 64 4 33 3 25 62 29
每行以一个或两个开头,表示它属于哪个批次。我正在尝试使用字符串流读取每一行并将结果存储在一个结构中,第一个数字对应于批号,后面的 32 个整数对应于内容,属于结构向量。我一直在为此苦苦挣扎,我遵循了此处找到的解决方案:How to read line by line
生成的程序如下:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
const string record1("records.txt");
// declaring a struct for each record
struct record
{
int number; // number of record
vector<int> content; // content of record
};
int main()
{
record batch_1; // stores integers from 1 - 64
record batch_2; // stores integers from 65 - 128
record temp;
string line;
// read the data file
ifstream read_record1(record1.c_str());
if (read_record1.fail())
{
cerr << "Cannot open " << record1 << endl;
exit(EXIT_FAILURE);
}
else
cout << "Reading data file: " << record1 << endl;
cout << "Starting Batch 1..." << endl;
read_record1.open(record1.c_str());
while(getline(read_record1, line))
{
stringstream S;
S << line; // store the line just read into the string stream
vector<int> thisLine; // save the numbers read into a vector
for (int c = 0; c < 33; c++) // WE KNOW THERE WILL BE 33 ENTRIES
{
S >> thisLine[c];
cout << thisLine[c] << " ";
}
for (int d = 0; d < thisLine.size(); d++)
{
if (d == 0)
temp.number = thisLine[d];
else
temp.content.push_back(thisLine[d]);
cout << temp.content[d] << " ";
}
if (temp.number == 1)
{
batch_1.content = temp.content;
temp.content.clear();
}
thisLine.clear();
}
// DUPLICATE ABOVE FOR BATCH TWO
return 0;
}
程序编译并运行,返回值为 0,但循环中的 cout 语句不执行,因为唯一的控制台输出是:
Starting Batch 1...
此外,如果第二批的代码重复,我会遇到分段错误。很明显,这不能正常工作。我不精通阅读字符串,因此将不胜感激。另外,如果这些行没有相同数量的条目(例如,一行有 33 个条目,另一行有 15 个),我该怎么办?
【问题讨论】:
-
这里
S >> thisLine[c];值thisline[c]不存在 - 您需要使用push_back成员函数向向量添加元素。 -
或者至少用
vector<int> thisLine(33,0)初始化它 -
我已经尝试过了,结果是否定的。刚刚又做了一次,我仍然得到与上面相同的结果....?
-
尝试将其存储到单独的 int 中,然后将其推送到向量中。
int temp;/S >> temp;/thisline.push_back(temp); -
这里是另一个问题:
if (d == 0) temp.number = thisLine[d]; else temp.content.push_back(thisLine[d]); cout << temp.content[d] << " ";当d为0 时,temp.content可能仍为空,因此访问temp.content[d]可能会失败。如果你改用temp.content.at(d),你会得到一个std::out_of_range异常。
标签: c++ stringstream read-write