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
)
solved Not getting output in case of string