首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ PlaySound()出现错误

C++ PlaySound()出现错误
EN

Stack Overflow用户
提问于 2019-12-15 07:19:51
回答 1查看 118关注 0票数 0

我正在尝试使用C++中的PlaySound();函数。我想让用户输入他们想要播放的文件。但是当我将变量放在PlaySound()中时,它会给我一个错误。这是代码,

代码语言:javascript
复制
#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。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-15 07:41:54

不能将TEXT()宏与变量一起使用,只能与编译时字符/字符串文字一起使用。您需要改用std::string::c_str()方法。

此外,TEXT()L前缀添加到指定标识符的事实意味着您正在为Unicode编译您的项目(即UNICODE是在预处理过程中定义的),这意味着PlaySound() (作为TCHAR-based宏本身)将映射到PlaySoundW(),后者期望宽强作为输入,而不是窄字符串。因此,您需要调用PlaySoundA()来匹配std::string的使用。

试试这个:

代码语言:javascript
复制
#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 ):

代码语言:javascript
复制
#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;
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59340003

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档