string subscript out of range

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] = '!';
}
Last edited on
try element[i]
string[i] is nonsense; it should have thrown warnings or errors on that
and, '!' would help too. no clue what ! does without quotes...

you may as well try range based for loop and get rid of the length and integer while you are at it.
for( auto &c : element)
c = '!';
cout << element;

or you can use std::fill
Last edited on
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 :)
Last edited on
You can also use std:fill()

 
std::fill(element.begin(), element.end(), '!');

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <cstring>
#include <string>
using namespace std;

int main()
{
   string element( strlen( "test" ), '!' );
   cout << element;
}
Last edited on
I will also edit my first post to show the correct code

PLEASE don't do that (though clearly it is too late).

By editing your post it makes the follow-up posts by others meaningless since they comment on code that is no more.

Leave the mistakes, and add another comment that shows corrected code.
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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.
Topic archived. No new replies allowed.