【问题标题】:ofstream not writing to end of existing text file in c++ofstream 未写入 C++ 中现有文本文件的末尾
【发布时间】:2015-10-03 03:05:49
【问题描述】:

它不会附加到我用 cin 指定的已创建文本文件(其中包含内容)的末尾,即使我在那里有 out2.open(tablename2, std::ofstream::out | std::ofstream::app);out2 << v2[i];

完整代码:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>
#include <vector>  
#include <iomanip>
#include <stdio.h>

using namespace std;
using std::vector;
using std::string;

void insertit(std::vector<std::string>& v, std::vector<std::string>& v2, std::string insertedstr) 
{
    std::string tablename2;
    cout << "Enter file name with the extension " << endl;
    std::getline(std::cin, tablename2);
    for (int w = 0; w < v.size(); w++) {
        cout << v[w] << ": ";
        cin.ignore();
        std::getline(std::cin, insertedstr);
        v2.push_back(insertedstr + " ");
        insertedstr.clear();
    }

    //below, why is it not writing to the file you specified from cin >>tablename2?
    std::ofstream out2(tablename2);
    out2.open(tablename2, std::ofstream::out | std::ofstream::app);

    for (int i = 0; i < v2.size(); i++) {
        out2 << v2[i];
    }

    out2.close();
    v2.clear();
    cout << "The record has been inserted into " << tablename2 << endl;
}

int main() 
{
    std::vector<std::string> v = {"author", "title"};
    std::vector<std::string> v2;
    std::string insertedstr;

    insertit(v, v2, insertedstr);

    return 0;
}

有什么想法吗?

【问题讨论】:

    标签: c++ ofstream


    【解决方案1】:

    构造函数已经打开了文件,虽然不是附加模式。我不清楚这是做什么的(我查看了 http://en.cppreference.com/w/cpp/io/basic_filebuf/open ,这并没有太大帮助,而且我不是标准向导)。如果你的构造函数看起来像

    std::ofstream out2(tablename2, std::ofstream::out | std::ofstream::app);
    

    并且您删除了 out.open(....) 调用,您的代码可以正常工作(使用 gcc 4.8.4 测试 - 我删除了 #include "stdafx.h")。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-19
      • 1970-01-01
      • 2014-10-26
      • 2015-02-13
      • 1970-01-01
      相关资源
      最近更新 更多