Selva Jove
Selva Jove

Reputation: 49

Disappeared characters in String But Accessed with index

In the following program,

int main()
{
  int i;
  string a;//unallocated string;

  for( i=0;i<26;i++)
  {
     a[i]=i+97;// trying to write a char at index i of a
  }
  cout<<" a[i] : ";

  for(i=0;i<26;i++)
  {
     cout<<a[i];// printing the characters 
  }

  cout<<"\n a as string : "<<a; // the string disappeared
}

Output :

a[i] : abcdefghijklmnopqrstuvwxyz

a as string :

My questions are

Upvotes: 3

Views: 112

Answers (1)

Jonathan Mee
Jonathan Mee

Reputation: 38939

When you do a[i] you are using string::operator[] which explicitly says:

Returns a reference to the character at specified location pos. No bounds checking is performed

a is default constructed so it will have a size of 0. You are trying to index outside those bounds, so anything you read or write there is undefined.

It looks like you're using 26 as a magic number for the upper bound for your loops. Instead use size(a) (or before C++17 use a.size()). Then if you wanted to execute your loops 26 times, just initialize a like this: string a(26, '\0')

Live (Slightly Improved) Example

EDIT:

As pointed out by AndyG C++ does provide us with better ways of initializing our strings in this case iota is an excellent choice. Instead of your initialization for loop you could use:

iota(begin(a), end(a), 'a')

I've updated the example to include this.

Upvotes: 10

Related Questions