-3
#include <bits/stdc++.h>
using namespace std;

int main()
{
    string s;
    s[0] = 'a';
    cout << s << endl;
    return 0;
}

I used this code and ran, but no output is coming don't know why?

But if am using s = ""; then also no output.

But when I use s = " "; then output comes why does this happen?

drescherjm
  • 10,365
  • 5
  • 44
  • 64
  • 1
    `s[0] = 'a';` is undefined behavior. You can't access positions of the string that don't exist. `s` is empty when this is called so `s[0]` is out of bounds. – drescherjm Apr 11 '21 at 14:29
  • ***But when I use s = " "; then output comes why does this happen?*** Because in this case then s has a length of 1 instead of 0. With a length of 1, `s[0]` would be a valid operation. The clear point here for you to remember that accessing out of bounds indices does not expand the string and that doing so is undefined behavior / breaking the rules of the language. – drescherjm Apr 11 '21 at 14:30
  • Please read [Why should I not #include ?](https://stackoverflow.com/q/31816095) and [Why using namespace std is bad practice](https://stackoverflow.com/questions/1452721). – prapin Apr 11 '21 at 14:43

2 Answers2

0

See the notes here you are trying to access the first (zeroth) character in a string without any characters. This is undefined behavior.

West
  • 722
  • 7
  • 16
0

You are using an uninitialized string, so assigning a to s[0] does nothing or does undefined behavior. To do this, you have to give s a size, as the options below:

Option 1: Resize

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string s;
    s.resize(10);
    s[0] = 'a';
    cout << s << endl;
    return 0;
}

Option 2: Push Back

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string s;
    s.push_back('a');
    cout << s << endl;
    return 0;
}

Option 3: +=

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string s;
    s += 'a';
    cout << s << endl;
    return 0;
}

There are more options, but I won't put them here. (one might be append)