Page 1 of 1

how can i input a string which has spaces into a char array?

Posted: Fri Jun 25, 2004 5:40 pm
by Morning
if i don't use gets(),how can i do that?
djfiejf fjiejfi fjeifjef -> char a[255]
cin.readLine()?how to use it?

Posted: Fri Jun 25, 2004 6:57 pm
by misof
one possibility: (I'm not sure whether getline works with a char array, but this should work.)

Code: Select all

string S;
getline(cin,S);
// now you either  use S.c_str(), or: 
char ch[100];
int sl=S.length();
for (int i=0;i<sl;i++) ch[i]=S[i];

Posted: Fri Jun 25, 2004 11:43 pm
by Krzysztof Duleba
Well, that's not a good idea to copy strings character by character. If one decides to copy a string to a char array, the proper code should look like
[cpp]char ch[100];
strcpy(ch, S.c_str());[/cpp]