Jump to content
  • Advertisement
Sign in to follow this  
2122

accepting multiple words from the user

This topic is 4526 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

The book I have stopped before explaining how to proper get input from the user that contains spaces. A string can work, but it won't work well. What kind of variable can take multiple words, and how do I use it? Thanks again for all the help :)

Share this post


Link to post
Share on other sites
Advertisement
You will want to use a string still, you will just need to use a differnt method of obtaining input.

Right now you are probabally doing something like this:

string input;
cout << "Enter your name:" << endl;
cin >> input;

That works for text without spaces, but as soon as you get a space, the rest of the text is discarded. Instead what you will need to do is use the getline function. Now you will have something like:

string input;
cout << "Enter your name:" << endl;
getline(cin, input);

And it will work properly, the user just has to hit return when they are done.

That's about it, don't forget to include string and iostream. Good luck!

Share this post


Link to post
Share on other sites
Yucky c++ code :) I don't like c++ i/o at all. I like to control my own error flags and input buffers.

I would suggest using fscanf. For example, if you wanted to read in 2 words and then an integer:

fscanf(stdin, "%s %s %d", buffer1, buffer2, &mynumber);
//uses the same format string as printf

You can replace stdin with a FILE * to read from a file too. The only downside is that you need to know the order of the variables. On the plus side, the spaces between the variables could be any number of spaces, tabs, and newlines.

Share this post


Link to post
Share on other sites
Actually, thanks alot for this guys! :D I am halfway through a C++ book now and it never said how to implement user input of multiple words with spaces. :D TY!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!