【问题标题】:Problems opening a file打开文件的问题
【发布时间】: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
}

如果需要更多信息,请告诉我。

【问题讨论】:

  • 使用调试器查找错误。并查看Why is iostream::eof inside a loop condition considered wrong?
  • 如果它崩溃了,也许你可以指出它崩溃在哪一行。这是非常有用的信息,它甚至可以帮助找到问题。
  • 您应该验证您的输入是否在读取后正确工作(而不是错误地使用eof()),例如,使用while (currentRecord != 12 &amp;&amp; monthfile &gt;&gt; oneline)

标签: c++ file file-io


【解决方案1】:

你没有包含它,所以我还是要说明它。

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

using namespace std;

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

【讨论】:

    最近更新 更多