1

I tried printing the string I created, but it doesn't exist. As you can see, the output shows length is 0:

#include <iostream>
#include <string>
using namespace std;

int main(){
  string a="";
  a[0]='a';
  a[1]='b';
  a[2]='c';

  cout<<"length of a: "<< a.length();
}

Output to the console is:

length of a: 0

0

4 Answers 4

2

You code has undefined behavior because you access elements out of bounds. The string has size() (which is the same as length()) 0 so a[0] and the others access elements that don't exist.

To make it work, you must resize() the string first.

Example:

string a;
a.resize(3);
a[0]='a';
a[1]='b';
a[2]='c';

You can also create the string with the proper length directly:

string a(3, '\0'); // create a string of length 3 filled with \0 chars
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks sir, I got it !
1

You are trying to acces an element whhich hasn't existed yet. a is an empty string so has size of 0, hence a[0] is undefined behavior because the size at least should be 1.

To avoid that use resize() before assigning to a, as follows

#include<iostream>
#include<string>
using namespace std;
int main(){
string a="";
a.resize(3);
a[0]='a';
a[1]='b';
a[2]='c';

cout<<"length of a: "<< a.length();
}

Or use push_back, as follows

#include<iostream>
#include<string>
using namespace std;
int main(){
string a="";
a.push_back('a');
a.push_back('b');
a.push_back('c');

cout<<"length of a: "<< a.length();
}

The first solution is better than the second to avoid reallocating.

Also see this Why is "using namespace std;" considered bad practice?

Comments

1

1)This string a=""; length of character here is 0 so it size also 0.

2)

a[0]='a';
a[1]='b';
a[2]='c';

it undefined behavior You are accessing out of bounds

3)so Add a.resize(3); to your code that is

#include<iostream>
#include<string>

using namespace std;

int main()
{
string a="";
a.resize(3);  // this will resize 
a[0]='a';
a[1]='b';
a[2]='c';
cout<<"length of a: "<< a.length();
}

Or string a="xxx"; fill some characters initially or use push_back(); like

a.push_back('a');
a.push_back('b');
a.push_back('c');

1 Comment

@Ajay Tyagi B18ME003 if you got the answer feel free accept any one of answers.
0

You should probably build a char array, and then you can use the from sequence string constructor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.