anonymous38653
anonymous38653

Reputation: 403

How do I create a string if I know characters at each index (in c++)

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

Upvotes: 1

Views: 54

Answers (4)

Ted Lyngmo
Ted Lyngmo

Reputation: 117178

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

Upvotes: 2

srilakshmikanthanp
srilakshmikanthanp

Reputation: 2389

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');

Upvotes: 1

asmmo
asmmo

Reputation: 7090

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?

Upvotes: 1

ShapeOfMatter
ShapeOfMatter

Reputation: 1011

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

Upvotes: 0

Related Questions