簡體   English   中英

無法轉換 'std::__cxx11::string {aka std::__cxx11::basic_string<char> }' 到 'LPCSTR {aka const char*}'</char>

[英]cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'LPCSTR {aka const char*}'

#include <iostream>
#include <string>
#include <sstream>
#include <windows.h>
#include <vector>

using namespace std;

int main() {
    string PNGFilePath, WEBPFilePath;
    int number, c;
    char title[256];

    cout << "Enter a Number: ";
    cin >> number;
    cout << endl;

    cout << "Title: ";
    cin.getline(title, 256, ';');

    cout << "Enter PNG directory: ";
    cin >> PNGFilePath;
    cout << endl;

    cout << "Enter WEBP directory: ";
    cin >> WEBPFilePath;
    cout << endl;

    std::string OldPNGFolder = std::string(PNGFilePath + "\\");
    c = 1;

    while (title[c] != '\0') {
        OldPNGFolder += title[c];
        c++;
    }

    std::string NewPNGFolder = std::string(PNGFilePath + "\\[");
    c = 1;
    NewPNGFolder += to_string(number);
    NewPNGFolder += "]";
    while (title[c] != '\0') {
        NewPNGFolder += title[c];
        c++;
    }

    MoveFile(OldPNGFolder, NewPNGFolder);
}

我嘗試添加“(OldPNGFolder.c_str()”,它仍然顯示相同的錯誤消息,也嘗試了 system(OldPNGFolder.c_str()); 仍然是相同的消息。

添加“LPCTSTR”顯示錯誤“錯誤:'OldPNGFolder'MoveFile(LPCTSTR OldPNGFolder,NewPNGFolder)之前的預期主表達式;”

有沒有辦法來解決這個問題???

你使用 Visual Studio 嗎?
如果你的項目的Character SetUse Unicode Character Set in the Project's Property window,MoveFile就是MoveFileW.
它的參數類型是LPCTSTR,也就是const wchar_t *,不是const char *。
您的錯誤不在於從字符串轉換為 const char *,而在於 MoveFile 中的參數類型錯誤。

您可以使用 MoveFileA, MoveFileA(OldPNGFolder.c_str(), NewPNGFolder.c_str());修復此問題或者如下所示將字符串轉換為 wstring 或 LPCWSTR。

wstring a2w(std::string & string_a)
{
    int length = MultiByteToWideChar(CP_UTF8, 0, string_a.c_str(), -1, NULL, 0);

    wchar_t* temp = new wchar_t[length];
    MultiByteToWideChar(CP_UTF8, 0, string_a.c_str(), -1, temp, length);

    wstring string_w = temp;
    delete[] temp;
    return string_w;
}

int main() {
    ...
    MoveFile(a2w(OldPNGFolder).c_str(), a2w(NewPNGFolder).c_str());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM