I was just doing some exercises and I got stuck on trying to change the characters of the string s
to the character x
, and this is my code below:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
using std::vector;
using std::array;
int main()
{
string s{ "Hello" };
for (auto &c : s)
char c{ "x" };
}
But it is throwing out the error:
'c': 'std::string' differs in levels of indirection from '_Elem &' T
If anyone could help that would be great
Use an algorithm:
std::fill(begin(s), end(s), ‘X’);
In your code you use a string literal to initialize a char
. You also don't want to define a new char
but assign to the reference you already got.
Try replacing your for loop with:
for(auto &c : s)
c = 'x'
Change the value of c
will change the characters in s
#include <iostream>
#include <vector>
#include <string>
using namespace std;
using std::vector;
using std::array;
int main()
{
string s{ "Hello" };
for (auto &c : s)
c = 'x';
cout << s;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.