I have a data file "records.txt" that has the following form:
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
Each line begins with either one or two, denoting which batch it belongs to. I am trying to use string stream to read in each line and store the results in a struct, with the first number corresponding to the batch number and the following 32 integers corresponding to the content, which belongs in the struct vector. I have been struggling mightily with this and I followed a solution found here: How to read line by line
The resulting program is the following:
#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;
}
The program compiles and runs with a return value of 0, but the cout statements within the loops do not execute since the only console output is:
Starting Batch 1...
In addition, if the code is duplicated for batch two I get a segmentation fault. So clearly this is not working properly. I'm not well versed with reading strings, so any help would be appreciated. Also, what would I do if the lines do not have an equivalent amount of entries (e.g. one line has 33 entries, another has 15)?