我正在尝试使用C++中的PlaySound();函数。我想让用户输入他们想要播放的文件。但是当我将变量放在PlaySound()中时,它会给我一个错误。这是代码,
#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;
}错误,identifier "Lfilename" is undefined 'Lfilename': undeclared identifier我正在使用Microsoft Visual Studio 2019。
发布于 2019-12-15 07:41:54
不能将TEXT()宏与变量一起使用,只能与编译时字符/字符串文字一起使用。您需要改用std::string::c_str()方法。
此外,TEXT()将L前缀添加到指定标识符的事实意味着您正在为Unicode编译您的项目(即UNICODE是在预处理过程中定义的),这意味着PlaySound() (作为TCHAR-based宏本身)将映射到PlaySoundW(),后者期望宽强作为输入,而不是窄字符串。因此,您需要调用PlaySoundA()来匹配std::string的使用。
试试这个:
#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;
}或者,改用std::wstring,因为Windows更喜欢使用Unicode字符串(基于ANSI的API在内部调用Unicode APIs ):
#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;
}https://stackoverflow.com/questions/59340003
复制相似问题