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

int main() {
    string s;
    s[0] = 'b';
    s[1] = 'a';
    s[2] = '\0';
    cout << s;
    return 0;
}

I declare a string in my code and than assign character values using array indices. When I print the string it gives me no output. My question is why not?

What is the reason that it is giving no output?

bindsniper001
  • 144
  • 2
  • 12
  • Replace `cout << s;` with `cout << s.length();` and you will understand, why it happens. Don't spam tags! There's nothing to C here. – S.M. Sep 22 '19 at 16:22
  • Please review your grammar in both the title and your description. [learn more](https://stackoverflow.com/help/how-to-ask) – Oxymoron Sep 22 '19 at 16:23
  • Please have a look at https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h?noredirect=1 – Aconcagua Sep 22 '19 at 16:29
  • When trying @S.M. 's advice, comment out character assignment as well, otherwise you still might not see any output (due to programme crash...). – Aconcagua Sep 22 '19 at 16:34
  • 1
    **Recommended reading:** [Why should I not #include ?](https://stackoverflow.com/q/31816095/560648) – Lightness Races in Orbit Sep 22 '19 at 17:20

1 Answers1

4

What you are trying to do has undefined behavior.

string s; default initializes (size is zero), then you access elements that are not there.

To solve it you can simply use string s = "ab"; or

std::string s;
s.push_back('b');
s.push_back('a');

or as @bindsniper001 suggested(you cannot add to the length of the string this way though):

std::string s2(2, ' ');
s2[0] = 'c';
s2[1] = 'd';

Live on godbolt

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
Oblivion
  • 6,320
  • 2
  • 9
  • 30
  • To add to this, you can modify the characters in a string using array syntax, but you can't add to its length that way. This would also be true if you were working with a raw array. You need to know how long the array is before you try to access its elements. – bindsniper001 Sep 22 '19 at 16:35