Home > other >  How to concatenate a variable between strings in an LPSTR?
How to concatenate a variable between strings in an LPSTR?

Time:08-05

I do have this function defined in windows playsoundapi.h.

PlaySound(L"D:\\resources\\English\\A.wav", NULL, SND_LOOP);

I want to concatenate a variable to replace "A.wav" in c . The variable is of type char* Can anyone suggest a solution to this please? Much appreciated.

CodePudding user response:

In C 17 or above use std::filesystem::path which is more handy for such scenario:

using std::filesystem::path;

path file = ...; // L"A.wav" // here can be wide characters things and regular character things - proper conversion is done implicitly
path base{L"D:\\resources\\English"};
PlaySound((base / file).c_str(), NULL, SND_LOOP);

Note that std::filesystem::path::c_str() returns const wchar_t* on Windows and const char * on other platforms.

Return value

The native string representation of the pathname, using native syntax, native character type, and native character encoding. This string is suitable for use with OS APIs.

CodePudding user response:

Simple enough

std::wstring var = ...;
PlaySound((L"D:\\resources\\English\\"   var).c_str(), NULL, SND_LOOP);

But if your variable is something other than a std::wstring, then that is a different question. Please add more details if that is the case.

EDIT

It seems the variable is type char*. One possible solution is to make a std::wstring variable from the char* variable

char* var = ...;
std::wstring tmp(var, var   strlen(var));
PlaySound((L"D:\\resources\\English\\"   tmp).c_str(), NULL, SND_LOOP);

This does assume that there are no encoding issues in copying from char to wchar_t but again that's a detail not provided in the question.

Also you should consider why the variable is char* in the first place. You are working with an API that requires wide characters, so why not use wide characters in your code?

  • Related