【问题标题】:Make console title bar display the value of a variable使控制台标题栏显示变量的值
【发布时间】:2016-10-12 20:32:42
【问题描述】:

我正在开发一个小程序,该程序最多可以计算用户给出的数字。他们输入的数字存储在变量limit 中。我希望该变量中的数字显示在类似这样的标题中:“最多计数 3000”或“限制设置为 3000”或类似的东西。我试过使用SetConsoleTitle(limit); 和其他东西,但它们不起作用。使用我在下面发布的代码,我收到以下错误:

“int”类型的参数与“LPCWSTR”类型的参数不兼容

如果这很重要的话,我目前正在使用 Visual Studio 2015。

#include <iostream>
#include <windows.h>    
#include <stdlib.h>        
using namespace std;

int main()
{
    begin:                            
    int limit;
    cout << "Enter a number you would like to count up to and press any key to start" << endl;
    cin >> limit;

    SetConsoleTitle(limit); // This is my problem
    int x = 0;
    while (x >= 0)
    {
        cout << x << endl;
        x++;

        if (x == limit) 
        {
            cout << "Reached limit of " << limit << endl;
            system("pause");
            system("cls");
            goto begin;
        }
    }
    system("pause");
    return 0;
}

【问题讨论】:

    标签: c++ variables console title


    【解决方案1】:

    SetConsoleTitle() 函数需要一个字符串作为它的参数,但你给它的是一个整数。一种可能的解决方案是使用std::to_wstring() 将整数转换为宽字符串。结果得到的 C++ 字符串与 SetConsoleTitle() 期望的以空字符结尾的宽字符字符串的格式不同,因此我们需要使用 c_str() 方法进行必要的转换。所以,而不是

    SetConsoleTitle(limit);
    

    你应该有

    SetConsoleTitle(to_wstring(limit).c_str());
    

    别忘了#include &lt;string&gt;to_wstring() 工作。

    如果您想要的标题不仅仅包含数字,则需要使用字符串流(在本例中为 wide character string stream):

    wstringstream titleStream;
    titleStream << "Counting to " << limit << " goes here";
    SetConsoleTitle(titleStream.str().c_str());
    

    要使字符串流工作,#include &lt;sstream&gt;。完整代码如下:

    #include <iostream>
    #include <string>
    #include <sstream>
    #include <windows.h>    
    #include <stdlib.h>     
    using namespace std;
    
    int main()
    {
    begin:
        int limit;
        cout << "Enter a number you would like to count up to and press any key to start" << endl;
        cin >> limit;
    
        wstringstream titleStream;
        titleStream << "Counting to " << limit << " goes here";
        SetConsoleTitle(titleStream.str().c_str());
        int x = 0;
        while (x >= 0)
        {
            cout << x << endl;
            x++;
    
            if (x == limit)
            {
                cout << "Reached limit of " << limit << endl;
                system("pause");
                system("cls");
                goto begin;
            }
        }
        system("pause");
        return 0;
    }
    

    【讨论】:

    • 感谢工作!但是你也可以在整数之前添加单词吗?所以它看起来像“计数到 integer 到这里
    • 我试过 SetConsoleTitle(to_wstring("Counting to " limit).c_str());
    • 更新了答案。
    • 太棒了!非常感谢!
    猜你喜欢
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2021-05-04
    • 2017-05-19
    • 1970-01-01
    相关资源
    最近更新 更多