c ++ FindFirstFile无法将const char转换为basic_string

时间:2015-09-04 09:57:11

标签: c++

FindFirstFile函数以某种方式不接受我的wstring(也不是字符串)作为参数传递。

我收到编译错误

Cannot convert const char[9] to std::basic_string
#include "stdafx.h"
#include <string>
#include <iostream>
#include <stdio.h>
#include <Windows.h>


using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    wstring path = "C:\\*.dmp";
    WIN32_FIND_DATA dataFile;
    HANDLE hFind;

    hFind = FindFirstFile (path.c_str(), &dataFile);


    cout << "The name of the first found file is %s \n" dataFile.cFileName << endl;
    FindClose hFind;
    getchar();
    return 0;
}

2 个答案:

答案 0 :(得分:1)

  

我收到编译错误

Cannot convert const char[9] to std::basic_string

您需要wide char literal正确初始化std::wstring

wstring path = L"C:\\*.dmp";
            // ^

你还错过了另一个<<

cout << "The name of the first found file is " << dataFile.cFileName << endl;`
                                            // ^^

另请注意,output formatting with std::ostreamprintf()格式字符串样式不同。注意我从上面的示例中删除了%s

答案 1 :(得分:0)

更改

const char path[] = "C:\\*.dmp";           // C-style string

hFind = FindFirstFile(path, &dataFile);    // Pass the string directly