I am trying to assign characters to a string. From what Ive read, a string is basically a c style array, so I think I should be able to do it the way I am, but I keep getting "string subscript out of range". I am trying to assign using string[] as shown in the code below. Is this actually possible?
I am wanting the string to contain all !'s after the loop
1 2 3 4 5 6
string element = "test";
int length = element.length();
for(int i = 0; i < length; i++)
{
element[i] = '!';
}
Sorry I just realised I had those typos in there, I was stupid and I didnt copy and paste it and just typed it in here, which now I see was a bad idea. But the suggestions you tried, I have in the original code.
I will try the for loop though and see if that helps. I will also edit my first post to show the correct code
Managed to fix it now, its now working. Thanks for the help :)
If you need to use a for loop that accesses all the elements of a string there are two other types of for loops you might want to consider. Either type makes it harder to go out of bounds than the usual for loop:
#include <iostream>
#include <string>
int main()
{
// test string
std::string str { "Test" };
// let's display the original string
std::cout << str << '\n';
// accessing each string element using iterator
for (auto itr { str.begin() }; itr != str.end(); ++itr)
{
// iterators are like pointers, but better
*itr = '!';
}
std::cout << str << '\n';
str = "Test";
// using a range-base for loop, AKA as a for_each loop
// have to use a reference to work on the original string
// otherwise it uses a copy
for (auto& itr : str)
{
itr = '?';
}
std::cout << str << '\n';
}
The better method for modifying the entire contents of a string is to use std::fill as others have suggested. Less code to type, easier to understand.