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

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
anonymous38653
  • 393
  • 4
  • 16

4 Answers4

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
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
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');
srilakshmikanthanp
  • 2,231
  • 1
  • 8
  • 25
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?

asmmo
  • 6,922
  • 1
  • 11
  • 25
0

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

ShapeOfMatter
  • 991
  • 6
  • 25