WHY is for loop is not working !

Hello
I want to fill a string with a number of spaces using for loop

1
2
3
4
for (int i=0 ; i<5 ; i++)
	{
		 name[i] = ' ' ;
	}


so it's not working
it gave string out of range
any Help !
Last edited on
how is name defined?
Last edited on
I'm just guessing here, but you might want to try making ' ' into '\0'
c string or c++ string ?
string name
name += ' ';
This will increase memory buffer allocated by name.
Or this: string name(5, ' ');

The reason why you have a crash is that the string size is to small (probably 0, if you didn't do anything with name)
This one actually works for me
1
2
3
4
5
string name [100] ;
	for (int i=0 ; i<5 ; i++ )
	{
		name [i] = ' ' ;
	}

now in order to fill a string with spaces I need to initialize size...
but I need to do something else


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;
struct name
{
	string sentence [100] ; // initialized size
} ;
int main ()
{
	name a [100] ;

	while (counter < 2)
	{
		getline (cin , a[counter].sentence) ;   // in order to make this line correct I will need to put the size of the sentence.......what size can I put to make the user enters a line
		index [counter] = a[counter].sentence .length () ;
		counter ++ ;
	}

}

Last edited on
When using std::getline() you don't need size initialization of a string. std::get line() returns a string of users input line length.
still syntax error
Surely, the code you've reported above wouldn't compile. counter, index, are neither declared, defined nor initialized.
1
2
3
4
5
string name [100] ;
for (int i=0 ; i<5 ; i++ )
{
    name [i] = ' ' ;
}

That code doesn't do what was asked, "I want to fill a string with a number of spaces using for loop".

Instead it allocates an array of 100 separate strings and sets the first five of them to contain just a single space.
Topic archived. No new replies allowed.