#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cctype>
usingnamespace std;
bool str_isalpha(string str) {
for (unsigned i = 0; i < str.size(); ++i) {
if (!isalpha(str[i])) returnfalse;
}
returntrue;
}
int main() {
ifstream in("records.txt");
if (!in.is_open()){
cerr << "whoops";
return 1;
}
ofstream out("formatted_records.txt");
vector<string> temp;
vector<string> headers;
string line;
for (int i = 0; getline(in,line); ++i) {
temp.push_back(line);
staticint k = -1;
if (str_isalpha(temp[i])) {
headers[++k] = temp[i];
temp[i] = "\n";
}
else {
temp[i] += "," + headers[k];
}
}
}
I'm not sure at all why. According to the debugger, temp[0] is the proper value right before the segfault, so I can't see why this isn't working. Any suggestions?
Ah, I found it! You see, headers is an empty vector! The segfault is caused because you use operator[] on an empty vector! A way to fix this could be the following:
1 2 3 4 5 6 7 8 9 10 11
vector<string> temp;
vector<string> headers;
string line;
string tmp; //<-add this here
//...
//and use it like this
tmp=temp[i];
headers.push_back(tmp);
k++;
EDIT: Still, what I said in the first post is important! Don't forget to fix that problem too somehow...
EDIT 2: Or you could just do headers.push_back(temp[i]); k++; lol... I feel so stupid now...