Reputation: 99
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;
}
Upvotes: 1
Views: 206
Reputation: 48258
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
Upvotes: 2