【问题标题】:C++ Casting out a int into stringC ++将int转换为字符串
【发布时间】:2021-10-29 01:05:12
【问题描述】:

我打算更改我的x[] 数组中的元素,以排除像 1、2、3、4 这样的数字。但是一旦我执行了代码。它将显示此错误消息。

error: no matching function for call to 
std::__cxx11::basic_string<char>::basic_string(int&)

请任何人都可以帮助我做任何事情来改变我的元素而不是使用 for 循环?我可以一一更改,我想一起更改,以防节省时间和编写的代码量。

#include <iostream>

using namespace std;

string x[] = {"X", "O", "X", "O"};

int main()
{
    cout << x[0] + x[1] + x[2] + x[3] << endl;

    for (int i = 0; i < 4; i++){
        x[i] = (string)i;
    }

    cout << x[0] + x[1] + x[2] + x[3] << endl;

    return 0;
}

【问题讨论】:

标签: c++ string numbers tostring


【解决方案1】:

这是错误的原因:

x[i] = (string)i;

阅读here:如何使用函数std::to_string,以便将数字转换为字符串

std::to_string(i);

#include <iostream>

std::string x[] = {"X", "O", "X", "O"};

int main()
{
    std::cout << "Before: " << x[0] + x[1] + x[2] + x[3] << std::endl;
    for (int i = 0; i < 4; i++)
    {
        x[i] = std::to_string(i);
    }
    std::cout << "after: " << x[0] + x[1] + x[2] + x[3] << std::endl;
 return 0;
}

这里是示例:https://ideone.com/X4dEdz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    相关资源
    最近更新 更多