[英]ofstream not writing to end of existing text file in c++
它沒有附加到我用cin
指定的已創建文本文件(其中包含內容)的out2.open(tablename2, std::ofstream::out | std::ofstream::app);
,即使我有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;
}
任何想法為什么?
構造函數已打開該文件,但未處於追加模式。 我不清楚這是做什么的(我查看了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"
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.