【发布时间】:2019-10-31 13:41:28
【问题描述】:
所以我做了一个函数,从两个文件中读取行并将它们写入一个向量。调用该函数两次,每个文件调用一次。现在我应该如何将向量的内容写入新文件?另外,我做得对吗?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
bool getFile(string filename, vector<string> & vecOfStrs){
ifstream in(filename.c_str());
if (in.fail()) {
cout << "No such file" << "\n";
return 1;
}
string str;
while (getline(in, str))
{
if (str.size() > 0)
vecOfStrs.push_back(str);
}
in.close();
return true;
}
int main(){
vector<string> A;
string lecCourse;
cout << "First file: ";
cin >> lecCourse;
string lab_ex;
cout << "Second file: ";
cin >> lab_ex;
string exit;
cout << "Name of exit file: " << "\n";
cin >> exit;
bool result = getFile(lecCourse, A);
bool result2 = getFile(lab_ex, A);
ofstream output;
output.open(exit.c_str());
if (output.fail()) {
cout << "error" << "\n";
return 1;
}
}
【问题讨论】:
-
请格式化您的代码并发布所有相关代码。您发布的代码将无法编译,因为它有几个语法错误。
-
建议 -- 如果您不熟悉 C++ 的某些方面,您应该编写较小的程序。不需要所有这些代码开始弄清楚如何将向量的内容写入文件。
int main() { std::vector<int> v = {1,2,3}; std::ofstream output("out.txt"); ...}就是你所需要的,然后尝试填写...。
标签: c++ vector fstream ofstream