使用 ofstream 写入文本文件时断言失败

Assertion failure when writing to a text file using ofstream

本文关键字:断言 失败 文件 文本 ofstream 使用      更新时间:2023-10-16

我正在尝试将一些字符串数据写入我从用户那里读取的.txt文件中,但这样做之后,程序关闭而不是继续,当我检查.txt文件内的结果时,我看到了一部分数据,然后是一些乱码,然后是断言失败错误!代码如下:

#include "std_lib_facilities.h"
#include <fstream>
using namespace std;
using std::ofstream;
void beginProcess();
string promptForInput();
void writeDataToFile(vector<string>);
string fileName = "links.txt";
ofstream ofs(fileName.c_str(),std::ofstream::out);
int main() {
//  ofs.open(fileName.c_str(),std::ofstream::out | std::ofstream::app);
beginProcess();
return 0;
}
void beginProcess() {
vector<string> links;
string result = promptForInput();
while(result == "Y") {
for(int i=0;i <= 5;i++) {
string link = "";
cout << "Paste the link skill #" << i+1 << " below: " << 'n';
cin >> link;
links.push_back(link);
}
writeDataToFile(links);
links.clear(); // erases all of the vector's elements, leaving it with a size of 0
result = promptForInput();
}
std::cout << "Thanks for using the program!" << 'n';
}
string promptForInput() {
string input = "";
std::cout << "Would you like to start/continue the process(Y/N)?" << 'n';
std::cin >> input;
return input;
}
void writeDataToFile(vector<string> links) {
if(!ofs) {
error("Error writing to file!");
} else {
ofs << "new ArrayList<>(Arrays.AsList(" << links[0] << ',' << links[1] << ',' << links[2] << ',' << links[3] << ',' << links[4] << ',' << links[5] << ',' << links[6] << ',' << "));n";
}
}

问题可能出在流写作过程中的某个地方,但我无法弄清楚。有什么想法吗?

您似乎正在用索引 0-5 填充 6 个向量,但是在您的 writeDataToFile 函数中正在取消引用链接[6],这超出了原始向量的界限。

另一件事与您的问题无关,但很好的做法:

void writeDataToFile(vector<string> links) 

正在声明一个执行向量副本的函数。除非你想专门复制你的输入向量,否则你很可能想要传递一个常量引用,比如 tso:

void writeDataToFile(const vector<string>& links)