Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

c++ - Not getting output in case of string

#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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...