【问题标题】:C++ PlaySound() giving errorsC++ PlaySound() 给出错误
【发布时间】:2019-12-15 07:48:08
【问题描述】:

我试图使用 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;
}

错误, identifier "Lfilename" is undefined 'Lfilename': undeclared identifier 我正在使用 Microsoft Visual Studio 2019。

【问题讨论】:

  • Edit 包含您收到的错误消息的问题。

标签: c++ playsound


【解决方案1】:

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

另外,TEXT()L 前缀添加到指定标识符的事实意味着您正在为Unicode 编译项目(即UNICODE 在预处理期间定义),这意味着PlaySound()(作为@基于 987654329@ 的宏本身)将映射到 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 2013-10-14
    • 1970-01-01
    相关资源
    最近更新 更多