【问题标题】:C++ writing content of a vector to a txt class?C ++将向量的内容写入txt类?
【发布时间】: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&lt;int&gt; v = {1,2,3}; std::ofstream output("out.txt"); ...} 就是你所需要的,然后尝试填写...

标签: c++ vector fstream ofstream


【解决方案1】:
#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;
    }
}

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

【讨论】:

  • 那么拉多斯拉夫..请确保正确回答了这个问题。
猜你喜欢
  • 1970-01-01
  • 2019-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-17
  • 1970-01-01
  • 2016-03-02
  • 1970-01-01
相关资源
最近更新 更多