I was trying to use the PlaySound(); function in C++. I want to take user input on what file they want to play. But when I put the variable in PlaySound(); It gives me an error. Here is the code,
#include <string>
#include <Windows.h>
using namespace std;
int main()
{
cout << "Enter song name...\nMake sure the song is in the same folder as this program\n";
string filename;
getline(cin, filename);
cout << "Playing song...\n";
bool played = PlaySound(TEXT(filename), NULL, SND_SYNC);
return 0;
}
Error,
identifier "Lfilename" is undefined
'Lfilename': undeclared identifier
I am using Microsoft Visual Studio 2019.
You can't use the TEXT()
macro with a variable, only with a compile-time character/string literal. You need to use the std::string::c_str()
method instead.
Also, the fact that TEXT()
is adding the L
prefix to the specified identifier means you are compiling your project for Unicode (ie UNICODE
is defined during preprocessing), which means PlaySound()
(being a TCHAR
-based macro itself) will map to PlaySoundW()
, which expects a wide strong as input not a narrow string. So you need to call PlaySoundA()
instead to match your use of std::string
.
Try this:
#include <string>
#include <Windows.h>
using namespace std;
int main() {
cout << "Enter song name...\nMake sure the song is in the same folder as this program\n";
string filename;
getline(cin, filename);
cout << "Playing song...\n";
bool played = PlaySoundA(filename.c_str(), NULL, SND_SYNC);
return 0;
}
Alternatively, use std::wstring
instead, since Windows APIs prefer Unicode strings (ANSI-based APIs call the Unicode APIs internally):
#include <string>
#include <Windows.h>
using namespace std;
int main() {
wcout << L"Enter song name...\nMake sure the song is in the same folder as this program\n";
wstring filename;
getline(wcin, filename);
wcout << L"Playing song...\n";
bool played = PlaySoundW(filename.c_str(), NULL, SND_SYNC);
return 0;
}