Cat Man
Cat Man

Reputation: 5

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);
}

I tried adding "(OldPNGFolder.c_str()" and it still shows the same error message, also tried system(OldPNGFolder.c_str()); and still the same message.

Adding "LPCTSTR" shows the error "error: expected primary-expression before 'OldPNGFolder' MoveFile(LPCTSTR OldPNGFolder, NewPNGFolder);"

Is there a way to fix this???

Upvotes: 0

Views: 1065

Answers (1)

secuman
secuman

Reputation: 539

Do you use Visual Studio?
If your project's Character Set is Use Unicode Character Set in the Project's Property window, MoveFile means that MoveFileW.
It's parameter type is LPCTSTR, that is const wchar_t *, not the const char *.
Your error is not in converting from string to const char *, just in parameter type error in MoveFile.

You can fix this by use MoveFileA, MoveFileA(OldPNGFolder.c_str(), NewPNGFolder.c_str()); or by convert string to wstring or LPCWSTR as below.

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());
}

Upvotes: 0

Related Questions