【问题标题】:Using Vector array variable in functions C++ [closed]在函数 C++ 中使用向量数组变量 [关闭]
【发布时间】:2017-11-03 21:20:38
【问题描述】:

我想将下面代码中变量name 中的数据保存到我的输出文件data.txt 似乎很容易?

不,因为我正在扫描 .exe 的根 "." 目录中的文件,然后将它们输出到 cmd 很容易,为什么我还要努力简单地输出到文件?

我查看了thisthis 链接。他们提供了一点帮助。

任何建议或意见将不胜感激。

原初处女code

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
#include <experimental/filesystem> 
#include <fstream>

using namespace std;

std::vector<std::string> get_filenames(std::experimental::filesystem::path path)
{
    namespace stdfs = std::experimental::filesystem;
    std::vector<std::string> filenames;
    const stdfs::directory_iterator end{};
    for (stdfs::directory_iterator iter{ path }; iter != end; ++iter)
    {
        if (stdfs::is_regular_file(*iter)) 
            filenames.push_back(iter->path().string());
    }
    return filenames;
}



void Dirloop(){
    for (const auto& name : get_filenames(".")) std::cout << name << '\n';
}


void Outfile() {

    std::ofstream outputFile("data.txt", std::ios::out);
    outputFile << name << std::endl;
    outputFile.close();
    cout << "Generated data.txt!\n";
}

int main()
{
    Dirloop();
    Outfile();
    std::getchar();
    return 0;
}

【问题讨论】:

  • outputFile &lt;&lt; name &lt;&lt; std::endl; name 来自哪里?很难就修复显然不可能的代码提出建议。
  • 您在DirLoop 函数中声明了name,但您试图在Outfile 中使用它。
  • 更改Outfile,使其将name作为参数,并从Dirloop调用它。它还应该以std::ios::app 模式打开文件,以便每次都添加到文件中而不是覆盖它。

标签: c++ windows console-application


【解决方案1】:

main() 中致电get_filenames。然后您可以将向量作为参数传递给Dirloop()Outfile()

void Dirloop(const std::vector<std::string> &filenames){
    for (const auto& name : filenames) {
        std::cout << name << '\n';
    }
}


void Outfile(const std::vector<std::string> &filenames) {

    std::ofstream outputFile("data.txt", std::ios::out);
    for (const auto& name : filenames) {
        outputFile << name << '\n';
    }
    outputFile.close();
    cout << "Generated data.txt!\n";
}

int main()
{
    std::vector<std::string> filenames = get_filenames(".");
    Dirloop(filenames);
    Outfile(filenames);
    std::getchar();
    return 0;
}

【讨论】:

  • 谢谢,我收到错误错误:C2440: 'initializing': cannot convert from... in VC 2015 有什么想法吗?我认为它缺少转换字符?
  • 错字,get_filenames 应该是get_filenames()
猜你喜欢
  • 1970-01-01
  • 2017-04-24
  • 2015-05-28
  • 2013-03-22
  • 1970-01-01
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多