-1
#include <bits/stdc++.h>

using namespace std;

int main(int argc, char const *argv[])
{
    
    int i=0;

    string s1 = "";

    s1[i++]='F';
    s1[i++]='U';
    s1[i++]='A';
    s1[i++]='A';
    s1[i++]='D';
    
    cout << s1;

    return 0;
}
James Z
  • 12,209
  • 10
  • 24
  • 44
  • 3
    `s1` is *empty*, any indexing into it will be *out of bounds* and lead to *undefined behavior*. Do e.g. `s1 += 'F'` instead. – Some programmer dude Jul 11 '21 at 11:04
  • 2
    And please read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) Doing `using namespace std;` is also [a bad habit](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) but usually considered okay for small examples. – Some programmer dude Jul 11 '21 at 11:05
  • 2
    Similar code will actually work in C, if you replace `string` by `char s1[99] = ""`. Maybe you took your code from someone who programmed C and not C++? Or from a very old book? – anatolyg Jul 11 '21 at 11:09

2 Answers2

3

You're trying to modify elements in an empty string.

If you want your code to work there are several ways to do this:

  • add elements to s1, you can use s1 += 'A' or s1.push_back('A') instead.
  • Allocate enough space to modify each element by doing s1.resize(5) after string s1 = "";.

And possibly more, but that should get you started. Think of std::string as an array of characters. If your array is empty, you either have to resize it or add things to it.

Note: Don't use #include <bits/stdc++.h> just do #include <string>.

Note: Avoid using using namespace std;

ShadowMitia
  • 2,411
  • 1
  • 19
  • 24
2

s1 is empty, any indexing into it will be out of bounds and lead to undefined behavior. Do e.g. s1 += 'F' instead. – Some programmer dude

anatolyg
  • 26,506
  • 9
  • 60
  • 134