代码之家  ›  专栏  ›  技术社区  ›  Stelios Papamichail

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

  •  0
  • Stelios Papamichail  · 技术社区  · 7 年前

    我试图将一些字符串数据写入一个从用户那里读取的.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编写过程中的某个地方,但我无法解决。 有什么想法吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   divinas    7 年前

    您似乎在用索引0-5填充一个包含6个元素的向量,但是在writedatatofile函数中,正在取消引用超出原始向量边界的链接[6]。

    另一件与你的问题无关的事情是良好的实践:

    void writeDataToFile(vector<string> links) 
    

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

    void writeDataToFile(const vector<string>& links)
    
    推荐文章