1

I am planning to change the elements inside the array of my x[] to cast out the number like 1, 2, 3, 4. But once i execute the code. it will show this error message.

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

Please anyone can help me to do anything to change my elements inside instead of using for loop? I can change it one by one by I want to change it all together just in case to save time and the amount of code written.

#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;
}
110f716c
  • 100
  • 1
  • 2
  • 8
  • 2
    Use [`std::to_string`](https://en.cppreference.com/w/cpp/string/basic_string/to_string) instead of casting to `string`. Possible duplicate: https://stackoverflow.com/a/26843934/11613622 – brc-dd Aug 30 '21 at 08:59
  • 1
    https://en.cppreference.com/w/cpp/string/basic_string/to_string – Alan Birtles Aug 30 '21 at 09:00

1 Answers1

2

this is the reason of the error:

x[i] = (string)i;

read here: how to use the function std::to_string so you can convert a number into a 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;
}

here the example: https://ideone.com/X4dEdz

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97