【发布时间】:2024-04-15 23:55:01
【问题描述】:
我对此很陌生。我试图打开一个文件,但程序每次都崩溃。在此之前,我已经打开了其他类似的文件。如果这有什么不同,我正在 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
}
如果需要更多信息,请告诉我。
【问题讨论】:
-
如果它崩溃了,也许你可以指出它崩溃在哪一行。这是非常有用的信息,它甚至可以帮助您找到问题。
-
您应该验证您的输入是否在读取后正确工作(而不是错误地使用
eof()),例如,使用while (currentRecord != 12 && monthfile >> oneline)。