【问题标题】:C++ Clearing wstringC++ 清除 wstring
【发布时间】:2013-12-22 10:50:37
【问题描述】:

我的问题是,过去在字符串上工作的方法都没有在 wstring 上工作。 所以我问我如何才能轻松清除 wstring 以达到审美目的。

我现在的代码:

    while (!foundRightOne)
    {
        wstring cTitle;
        ForegroundWindow = GetForegroundWindow();
        cout << "FRGW  " << ForegroundWindow << endl;

        int len = GetWindowTextLengthW(ForegroundWindow) + 1;
        wchar_t * windowTitle = new wchar_t[len];
        GetWindowTextW(ForegroundWindow, windowTitle, len);
        title += windowTitle;
        // OUTPUT
        cTitle = L"Title: ";
        cTitle += title;
        wcout << cTitle << endl;
        cTitle = ' ';
        //OUTPUT
        keyPress = getchar();
        system("CLS");
        if (keyPress == 'y' || keyPress == 'Y')
        {
            foundRightOne = true;
        }

    }

基本上,当我按下yY 时,它会循环播放,当我看到右边的cTitle 时按下它,并且在~20 个循环之后,cTitle 会完全填充上一个循环的文本。

【问题讨论】:

  • std::stringstd::wstring 除了存储的字符类型外完全相同。无论如何,空格不是清除字符串,字符文字不是宽字符,就像字符串文字不是宽字符串一样。
  • 代码没有测试用例。请提供“职称”的定义

标签: c++ wstring


【解决方案1】:

std::wstring::clear 应该可以工作,因为它和std::string 都是std::basic_strings。如果您遇到问题,请查看std::basic_string 文档。

#include <iostream>

int main()
{
    std::string regularString("regular string!");
    std::wstring wideString(L"wide string!");

    std::cout << regularString << std::endl << "size: " << regularString.size() << std::endl;
    std::wcout << wideString << std::endl << "size: " << wideString.size() << std::endl;

    regularString.clear();
    wideString.clear();

    std::cout << regularString << std::endl << "size: " << regularString.size() << std::endl;
    std::wcout << wideString << std::endl << "size: " << wideString.size() << std::endl;
}

输出:

regular string!
size: 15
wide string!
size: 12

size: 0

size: 0

这是指向该代码的ideone 链接。

【讨论】:

  • 谢谢。现在我真的很困惑。检查 size() 后显示为 0,但仍输出 OLD 标题。 [链接]i.imgur.com/W52gvIM.png - 截图
  • @Ufonautas 您是否尝试将其设置为空字符串? cTitle = "" 或通过 cTitle = std::wstring() 重新初始化它
猜你喜欢
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
  • 2018-07-13
  • 1970-01-01
  • 2020-10-14
  • 2012-11-12
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多