atavarecek atavarecek - 2 months ago 14
C++ Question

C++: Reading multiple inputs only to end of the line

How this program should work:

Enter 4 words:

this is bad

Bad input.


Enter 4 words:

hello you love it

Good input.

How I tried it:

#include <iostream>
#include <string>

using namespace std;

int main(void) {
cout << "Enter 4 words:" << endl;
string a, b, c, d;
cin >> a >> b >> c >> d;

It reads input after end of the line and I can't figure out how to limit it only to one line. Can you please point me what function I should use? I'll be very grateful for every answer.

Thank you all!


std::getline() should be used when the program's expected input comes from an interactive terminal.

That's what std::getline() does: it reads text until the newline character. operator>> doesn't do that, that's what std::getline() does, and that's what should be used to process a line of typed-in text. Use the right tool, for the right job.

Sadly, many C++ books and tutorials introduce >> too early, before introducing std::getline(), and use it in their examples, simply because it's easier and more convenient to have >> handle the required data type conversion. Unfortunately, this results in a wrong mindset settling in, where >> is thought to be the automatic choice for processing interactive input. It is not.

The correct approach is to use std::getline(). Then, if necessary, construct a std::istringstream, and use that to handle any type conversions from the entered input. Not only does that solve the immediate problem, it also solves the problem of unparsable input putting std::cin into a failed state, with all subsequent attempted input conversions failing as well -- that's another common pitfall.

So, use std::getline(), first:

#include <string>
#include <iostream>
#include <sstream>
#include <vector>

int main(void) {
   std::cout << "Enter 4 words:" << endl;
   std::string line;

   std::getline(std::cin, line);

And now, once the line of text is entered, it can be converted to a std::istringstream:

   std::istringstream i(line);

Followed by a loop to repeatedly invoke >> in order to count the words in this line. This part you can finish yourself.

P.S. Another common pitfall is using namespace std;. You should not do that, as well. The earlier good programming practices are acquired, the easier the subsequent road on the path towards C++ guru-ism will be.