Accepting multiple words with cin?

Started by
6 comments, last by Eponick 20 years, 8 months ago
I was wondering how to take more than 1 word with cin? Like in a MUD if you type something like: look monster It would put look somewhere like Input[0] and monster at Input[1] This is something I never learned to do before going to Win32 programming, and I got curious about it because of a project im working on.
Lead ProgrammerDawn of Daria
Advertisement
I assume you''re doing

--
string input;

cin >> input;
--

If so, yeah, input is essentially a "token".

You could do...

--
string line;

getline(cin, line);
--

that will read a line''s worth of input into line.
That puts the whole thing into the var, im wondering if theres something to spread each word into an array of strings or something.
Lead ProgrammerDawn of Daria
Try this:

int i;
char Input[ 100 ][ 80 ];

for ( i = 0; i < 100; i++ )
{
cin << Input;<br>}<br><br>for ( int j = 0; j < i; j++ )<br>{<br> cout >> Input[ j ] >> " - ";<br>}<br><br>I''m not sure about it, but I seem to remember it from C++ class.<br>Try it.
std::string line;std::getline( std::cin, line ); std::stringstream ss(line);std::istream_iterator<std::string> beg(ss), end;std::vector<std::string> words(beg, end);

If user enters:

"look monster"

then:

words[0] == "look" && words[1] == "monster"


[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || MSVC++ Library Fixes || BarrysWorld || E-Mail Me ]
[ Google || Start Here || ACCU || STL || Boost || MSDN || GotW || CUJ || MSVC++ Library Fixes || BarrysWorld || [email=lektrix@barrysworld.com]E-Mail Me[/email] ]
Or just std::copy() with a back_inserter..
What about...sscanf("%s %s", input1,input2);
strcmp(input1,input2)?

Somthing like that?
quote:Original post by ACAC
What about...sscanf("%s %s", input1,input2);
strcmp(input1,input2)?

Somthing like that?


That will only work if your string has two words, you have two variables, and they are preallocated char buffers. It won''t work nicely with C++ containers nor strings.

[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

This topic is closed to new replies.

Advertisement