使用 SAPI.H - 为什么我的程序只说第一个词

Using SAPI.H - why does my program only speak the first word?

本文关键字:第一个 程序 我的 SAPI 为什么 使用      更新时间:2023-10-16

我希望能够在程序中输入一个字符串,并使用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;
    }
}

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

输入

未正确读取。

std::cin >> text; 

读取一个空格分隔的令牌后停止。如果输入是"我是现代少将的典范"。 std::cin >> text;将在第一个空格停止阅读,并在text中仅提供"I"。该行的其余部分保留在流中等待读取。

std::getline(cin, text); 

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