[C ++将向量的内容写入txt类?

问题描述 投票:0回答:1

因此,我做了一个从两个文件中读取行并将其写入向量的函数。两次调用函数,每个文件一次。现在,我应该如何将向量的内容写入新文件?另外,我做对了吗?

#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++ vector fstream ofstream
1个回答
0
投票
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
using namespace std;
vector<string> A;
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()
    {
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());
for(int i=0;i<A.size();i++)
{
    output<<A[i]<<"\n";
}
if (output.fail()) {
    cout << "error" << "\n";
    return 1;
    }
}

希望!这可能会有所帮助:))]

© www.soinside.com 2019 - 2024. All rights reserved.