C++ 打开文件时出现问题
我对这方面还不太熟悉。我正试图打开一个文件,但程序每次都会崩溃。我以前打开过其他类似的文件,但这些文件都起作用了。我在视觉工作室工作,如果这有什么不同的话。任何帮助都将不胜感激C++ 打开文件时出现问题,c++,file,file-io,C++,File,File Io,我对这方面还不太熟悉。我正试图打开一个文件,但程序每次都会崩溃。我以前打开过其他类似的文件,但这些文件都起作用了。我在视觉工作室工作,如果这有什么不同的话。任何帮助都将不胜感激 #include <iostream> #include <fstream> using namespace std; void splitStringByCommas (string s, string pieces[]); struct month { string name; int o
#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
}
#包括
#包括
使用名称空间std;
void splitStringByCommas(字符串s、字符串片段[]);
结构月{
字符串名;
整数阶;
};
int main(int argc,const char*argv[]{
string baseDir=“C:\\Users\\Brian\\Desktop/”;
字符串onerecord[2];
字符串单线;
ifstream monthsfile;
monthfile.open(baseDir+“months.txt”);
int currentRecord=0;
月[12];
而(!monthfile.eof()&¤tRecord<12){
monthsfile>>oneline;
按逗号拆分字符串(单行,单列);
月份[currentRecord]。名称=onerecord[0];
月份[currentRecord].order=atoi(onerecord[1].c_str());
currentRecord++;
}
对于(inti=0;i您没有包含它,所以我还是要声明它
#include<string>
#include<iostream>
#include<fstream>
using namespace std;
#包括
#包括
#包括
使用名称空间std;
正如您所说,您的编译器正在向您显示问题的确切位置。您将其命名为splitStringByComma。请尝试此操作。使用调试器查找错误。然后查看。如果它崩溃,也许您可以指出它崩溃的行。这是非常有用的信息,甚至可能有助于您找到问题。您应该验证在阅读后,您的输入工作正常(而不是不正确地使用eof()
),例如,使用while(currentRecord!=12&&monthfile>>oneline)
。