即使我有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;
}
任何想法为什么?
答案 0 :(得分: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"
)。