accepting multiple words from the user
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 :)
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:
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:
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!
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!
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.
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.
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!
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement