【问题标题】:no suitable conversion function from "const std::string" to "char *" exists?不存在从“const std::string”到“char *”的合适转换函数?
【发布时间】:2021-09-09 16:24:22
【问题描述】:

我正在尝试制作一个简单的程序,列出目录中的所有 txt 文件,然后在其中附加 hello world,但在将向量传递给 WriteFiles 函数时遇到问题

这是我尝试修复它一段时间的以下代码,感谢任何帮助

    #define _CRT_SECURE_NO_WARNINGS
    #include <string>
    #include <vector>
    #include <iostream>
    #include <windows.h>
    #include <fstream>
    
    using namespace std;
    
    void ListFiles(vector<string>& f) // list all files
    {
        FILE* pipe = NULL;
        string pCmd = "dir /b /s *.txt ";
        char buf[256];
    
        if (NULL == (pipe = _popen(pCmd.c_str(), "rt")))
        {
            return;
        }
    
        while (!feof(pipe))
        {
            if (fgets(buf, 256, pipe) != NULL)
            {
                f.push_back(string(buf));
            }
    
        }
    
        _pclose(pipe);
    
    
    }
    
    void WriteFiles (const char* file_name)
    {
        std::ofstream file;
    
        file.open(file_name, std::ios_base::app); // append instead of overwrite
        file << "Hello world";
        file.close();
    
    }
    
    int main()
    {
    
        vector<string> files;
        ListFiles(files);
        vector<string>::const_iterator it = files.begin();
        while (it != files.end())
        {
            WriteFiles(*it); // the issue is here
            cout << "txt found :" << *it << endl; 
            it++;
        }
    
    }

【问题讨论】:

  • 尤达太多了。 FILE* pipe = _popen(pCmd.c_str(), "rt"); if (!pipe) return;.
  • 这并没有解决问题,而是养成使用有意义的值初始化对象的习惯,而不是默认构造它们并立即覆盖默认值。在这种情况下,这意味着将std::ofstream file; file.open(file_name, std::ios_base::app); 更改为std::ofstream file(file_name, std::ios_base::app);。此外,您不必致电file.close()。析构函数会这样做。
  • C++ 有一个文件系统库。我建议使用它而不是在 dir 上捎带。

标签: c++ vector


【解决方案1】:

WriteFiles(it-&gt;c_str()); 将解决问题。迭代器的作用很像指针,所以这就是您间接访问方法的方式。

【讨论】:

  • @Atrox 很抱歉,我现在无法为您调试它。使用调试器查看发生了什么。祝你好运
猜你喜欢
  • 2014-11-04
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-23
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
相关资源
最近更新 更多