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

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
Morning
Experienced poster
Posts: 134
Joined: Fri Aug 01, 2003 2:18 pm
Location: Shanghai China

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

Post 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?
"Learning without thought is useless;thought without learning is dangerous."
"Hold what you really know and tell what you do not know -this will lead to knowledge."-Confucius
misof
A great helper
Posts: 430
Joined: Wed Jun 09, 2004 1:31 pm

Post 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];
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post 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]
Post Reply

Return to “C++”