0

I'm fairly new at this. I'm trying to open a file, but the program crashes every time. I have opened other files like this before that has worked. I'm working on in Visual Studios if that makes any kind of difference. Any help would be appreciated.

#include <iostream>
#include <fstream>
using namespace std;

void splitStringByCommas (string s, string pieces[]);

struct month {
string name;
int order;
};

int main(int argc, const char * argv[]) {

string baseDir = "C:\\Users\\Brian\\Desktop/";

string onerecord [2];
string oneline;
ifstream monthsfile;
monthsfile.open (baseDir + "months.txt");
int currentRecord = 0;
month months[12];

while (!monthsfile.eof() && currentRecord < 12) {
    monthsfile >> oneline;
    splitStringByCommas(oneline, onerecord);
    months[currentRecord].name = onerecord[0];
    months[currentRecord].order = atoi(onerecord[1].c_str());
    currentRecord++;
}

for (int i=0; i<currentRecord; i++) {
    cout << months[i].name << endl;
}

return 0;
}


// This function splitStringByCommas is necessary
// and I give it to you for free.
// Do not change this.
void splitStringByCommas (string s, string pieces[]) {
size_t comma = 0;
int piece = 0;
while (comma != string::npos) {
    comma = s.find(',');
    pieces[piece++] = s.substr(0, comma);
    s = s.substr(comma+1);
}
pieces[piece] = s; // remainder
}

Please let me know if there is anymore info needed.

Brian
  • 1
  • 3
  • 3
    Use the debugger to find the error. And see [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/). – Remy Lebeau Dec 01 '15 at 02:23
  • 1
    If it crashes, perhaps you could indicate which line it crashes on. This is pretty useful information to have, and it might even help *you* to find the problem. – paddy Dec 01 '15 at 02:24
  • You should verify that your input worked correctly _after_ reading (and instead of this incorrect use of `eof()`), e.g., using `while (currentRecord != 12 && monthfile >> oneline)`. – Dietmar Kühl Dec 01 '15 at 02:52

1 Answers1

0

You didn't include it, so I'm going to state it anyway.

#include<string>
#include<iostream>
#include<fstream>

using namespace std;

Your compiler is showing you exactly where the issue is, as you stated. You named it splitStringByComma. Try this. Split a string in C++?

Community
  • 1
  • 1