打开文件时出现问题

时间:2015-12-01 02:17:46

标签: c++ file file-io

我对此很新。我试图打开一个文件,但程序每次都崩溃了。在此之前,我已经打开了这样的其他文件。我在Visual Studios工作,如果这有任何区别。任何帮助将不胜感激。

#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
}

如果还有更多信息,请告诉我。

1 个答案:

答案 0 :(得分:0)

你没有把它包括在内,所以无论如何我都会说出来。

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

using namespace std;

正如您所说,您的编译器正在向您显示问题的确切位置。你将它命名为splitStringByComma。试试这个。 Split a string in C++?

相关问题