如何循环BSTR

How to loop a BSTR?

本文关键字:BSTR 循环 何循环      更新时间:2023-10-16

我有一个包含大量字符的BSTR。

        BSTR theFile = NULL;
        int res = comSmartspeak -> readTheFile(fileName, &theFile);

我想读第一行,但我不知道怎么做。

这是我想出来的伪代码:

        string firstLine = "";
        for (int i = 0; i < SysStringLen(theFile) ; i++)
        {
            if (theFile[i] == 'n')
            {
                break;
            }else
            {
                firstLine += theFile[i] ;
            }
        }

我是vc++新手

//another option
BSTR comStr = ::SysAllocString(L"First line of textnSecond line of textnThird line of textnFourth line of text...");
    std::wstring ws(comStr, SysStringLen(comStr));
    std::wstring::size_type pos = ws.find_first_of('n');
    if (pos != std::wstring::npos)
    {
        std::wcout << ws.substr(0, pos);
    }

您可以这样做,假设您可以自由使用std::wstring,这样您就不必事先计算第一行的长度:

#include <Windows.h>
#include <iostream>
#include <string>
int main()
{
    BSTR a_bstr = ::SysAllocString(L"First line of textnSecond line of textnThird line of textnFourth line of text...");
    std::wstring wide_str;
    unsigned int len = ::SysStringLen(a_bstr);
    for (unsigned int i = 0; i < len; ++i)
    {
        if (a_bstr[i] != 'n')
            wide_str += a_bstr[i];
        else
            break;
    }
    // wide_str holds your first line
    std::wcout << "First line: " << wide_str << std::endl;
    ::SysFreeString(a_bstr);
    return 0;
}