gpt4 book ai didi

C++ PlaySound() 给出错误

转载 作者:行者123 更新时间:2023-11-27 22:32:23 25 4
gpt4 key购买 nike

我正在尝试使用 PlaySound(); C++中的函数。我想让用户输入他们想播放的文件。但是当我把变量放在 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;
}

错误,标识符“Lfilename”未定义'Lfilename': 未声明的标识符我正在使用 Microsoft Visual Studio 2019。

最佳答案

您不能使用 TEXT()带有变量的宏,仅带有编译时字符/字符串文字。您需要使用 std::string::c_str()方法代替。

此外,TEXT()L 前缀添加到指定标识符的事实意味着您正在为 Unicode 编译项目(即 UNICODE 是在预处理期间定义的),这意味着 PlaySound()(本身是一个基于 TCHAR 的宏)将映射到 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 API 更喜欢 Unicode 字符串(基于 ANSI 的 API 在内部调用 Unicode API):

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

关于C++ PlaySound() 给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59340003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com