Question in a string !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# include <iostream>
# include <algorithm>
# include <string>
using namespace std ;
int main ()
{
	string name ;
	name [5] = 'e' ; // initialize the 5th element of the string
	for (int i=0 ; i<5 ; i++)
	{
		name  += ' ';  //putting spaces from element 0 to 4 in the string
	}
        // print the string till the 5th element 
    for (int i=0 ; i<6 ; i++)
	{
		cout << name [i] ;
	}
	
	system ("Pause");
}



why is this code is not running ......string out of range
Last edited on
The funny thing is if this code was written this way it will work !

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# include <iostream>
# include <algorithm>
# include <string>
using namespace std ;
int main ()
{
	string name ;
	
	for (int i=0 ; i<5 ; i++)
	{
		name += ' ';
	}
	name [5] = 'e' ;    // Here is the chanage
	
    for (int i=0 ; i<6 ; i++)
	{
		cout << name [i] ;
	}
	
	system ("Pause");
}
closed account (28poGNh0)
I dont know It works for me what compiler do you use

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# include <iostream>
# include <conio.h>
using namespace std;

int main()
{
    string name ;

    for(int i=0 ; i<5 ; i++)
        name  += ' ';

    name [5] = 'e' ;

    for(int i=0;i<6;i++)
        cout << name[i];

    getch();
}

Last edited on
I know that code is working
but why is one is not

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# include <iostream>
# include <algorithm>
# include <string>
using namespace std ;
int main ()
{
	string name ;
	name [5] = 'e' ; // initialize the 5th element of the string
	for (int i=0 ; i<5 ; i++)
	{
		name  += ' ';  //putting spaces from element 0 to 4 in the string
	}
        // print the string till the 5th element 
    for (int i=0 ; i<6 ; i++)
	{
		cout << name [i] ;
	}
	
	system ("Pause");
}

1
2
	string name ;
	cout << "Length of string is: " << name.length() << endl; 

Output:
Length of string is: 0

It doesn't make sense to access elements outside the string, such as name[5].
Topic archived. No new replies allowed.