gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:31:53 26 4
gpt4 key购买 nike

我正在尝试将一些字符串数据写入我从用户那里读取的 .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";
}
}

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

最佳答案

您似乎正在填充一个包含 6 个元素的 vector ,索引为 0-5,但是在您的 writeDataToFile 函数中正在取消引用链接 [6],这超出了您的原始 vector 的范围。

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

void writeDataToFile(vector<string> links) 

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

void writeDataToFile(const vector<string>& links)

关于c++ - 使用 ofstream 写入文本文件时断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51135431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com