【问题标题】:Using SAPI.H - why does my program only speak the first word?使用 SAPI.H - 为什么我的程序只说第一个词?
【发布时间】:2016-05-21 13:32:09
【问题描述】:

我希望能够在程序中输入字符串并使用 MS-SAPI 让计算机说出该字符串。我正在用 C++ 做。这是我的代码:

#include "stdafx.h"
#include <sapi.h>
#include <iostream>
#include <string>

std::wstring str_to_ws(const std::string& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

int main(int argc, char* argv[]) {
    while(true) {
        std::cout << "Enter some words: " << std::endl; std::cout << ">> ";
        std::string text; std::cin >> text;
        std::cout << "" << std::endl;
        std::wstring stemp = str_to_ws(text);
        LPCWSTR speech_text = stemp.c_str();
        ISpVoice * pVoice = NULL;
        if (FAILED(::CoInitialize(NULL))) {}
        HRESULT hresult = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
    if (SUCCEEDED(hresult)) {
        hresult = pVoice->Speak(speech_text, 0, NULL); 
        pVoice->Release();
        pVoice = NULL;
    }
    ::CoUninitialize(); 
    return TRUE;
    }
}

问题是程序只说出字符串的第一个单词然后退出......我该如何解决这个问题?

【问题讨论】:

    标签: c++ windows text-to-speech sapi


    【解决方案1】:

    输入未被正确读取。

    std::cin >> text; 
    

    在读取一个以空格分隔的标记后停止。如果输入是“我是现代少将的典范”。 std::cin &gt;&gt; text; 将在第一个空格处停止阅读,并在 text 中仅提供“I”。该行的其余部分留在等待读取的流中。

    std::getline(cin, text); 
    

    可能更符合您的要求。 std::getline 将使用默认的行尾分隔符读取输入行末尾的所有内容。 std::getline 的其他重载允许您指定分隔符,使其成为一个很好的通用解析工具。

    【讨论】:

    • 非常感谢!这真的很有帮助!我通过std::getline(std::cin, text);得到它
    猜你喜欢
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    相关资源
    最近更新 更多