Mar 22, 2013 at 10:23am UTC
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 Mar 22, 2013 at 10:24am UTC
Mar 22, 2013 at 10:29am UTC
how is name
defined?
Last edited on Mar 22, 2013 at 10:58am UTC
Mar 22, 2013 at 10:53am UTC
I'm just guessing here, but you might want to try making ' ' into '\0'
Mar 22, 2013 at 11:39am UTC
name += ' ' ;
This will increase memory buffer allocated by name.
Mar 22, 2013 at 11:43am UTC
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
)
Mar 22, 2013 at 11:58am UTC
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 Mar 22, 2013 at 11:59am UTC
Mar 22, 2013 at 12:23pm UTC
When using std::getline() you don't need size initialization of a string. std::get line() returns a string of users input line length.
Mar 22, 2013 at 1:48pm UTC
Surely, the code you've reported above wouldn't compile. counter , index , are neither declared, defined nor initialized.