【发布时间】:2018-07-02 11:44:08
【问题描述】:
我正在尝试将一些字符串数据写入我从用户那里读取的 .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 编写过程的某个地方,但我无法弄清楚。有什么想法吗?
【问题讨论】:
-
胡言乱语可能会为正在发生的事情提供有用的提示。断言失败是否有调用堆栈?样本输入引发错误?从语义上讲,您所做的似乎是开放代码注入漏洞(目标文件的内容是否已执行?)。注意元素的实际数量,您正在编写 0..6 = 7 个元素但要求 0..5 = 6 个元素。
-
样本输入为:1,2,3,4,5,6。没错,我正在尝试访问 6 元素向量的第 7 个元素(我会尽快修复该问题)。我尝试在此处粘贴输出文件,但它的长度为 66k 字符!我应该像前几行一样粘贴吗?
-
您已经得到解决索引/计数问题的答案