c++ question. I need to be able to store words with spaces into a variable I was think a string variable. But it cant take spaces and I need it to so what should I do?? For instance if I wanted to store
"john smith williams" all into one variable how would I do it?
(C++)how can I make a string register spaces as well as the words?
Are you talking about reading a string into the program using cin? In that case, if s is a string object, instead of:
cin %26gt;%26gt; s;
Try:
getline(cin,s);
Reply:I think you're confusing a variable name with a variable value. Names cannot contain spaces, but a string variable can contain any character, even a space.
As a parallel, consider that an int variable can be named abc, but contain the integer 100. A string variable can be named def but contain the string value "The quick brown fox jumped over the lazy dog!" Even an exclamation point is legal in a string value.
Syntactically, this would be done in one of the following ways (depending on how the compiler handles strings):
char a_char_string[ 100 ];
CString a_cstring;
...
strcpy( a_char_string, "The quick brown fox jumped over the lazy dog!" );
a_cstring = "The quick brown fox jumped over the lazy dog!";
(As a side note, notice that variable names can -- and often do -- contain underscore characters to take the place of blanks, but it's crucial that you understand the distinction between a variable's name and its contents.)
Reply:In this answer, I'm assuming that you are doing something like this:
#include %26lt;string%26gt;
#include %26lt;iostream%26gt;
int main()
{
string var1, var2;
cin %26gt;%26gt; var1%26gt;%26gt; var2;
}
The results you are seeing are a result of the way the %26gt;%26gt; operator works, try this way instead:
getline(cin, var1);
That will read a whole line, spaces and all, into var1.
Reply:take a character variable and use gets() function
e.g
char str[50];
gets(str);
strawberry
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment