-1

I've been trying to make a program which requires me to read symbols until a new line. I saw a lot of people suggested getline() in similar problems, but I want to know if there is any other way to do it, mainly because of the way my code works so far.

#include <iostream>
#include <string>

int main()
{
    std::string str;
    while(true)
    {
        std::cin >> str;
        std::cout << str << " ";
        //some actions with token
    }
}

The thing I find interesting about this code is that it first reads all the inputs, and then when I press Enter, it writes them all, for example, if I input

1 2 3 a b c

I get the output after I press enter. So is there a way to use that to my advantage and only take one line of input?

Tomas Smith
  • 11
  • 1
  • 3

1 Answers1

0

You are seeing the output behavior after enter due, most likely, to the buffer being flushed. In most cases I'm aware of, this is just an artifact of how you are interacting with the stdout of your terminal, and shouldn't change how stdin is read at all.

Your best bet is definitely istream::getline, which has a great example on C++ Reference:

// istream::getline example
#include <iostream>     // std::cin, std::cout

int main () {
  char name[256], title[256];

  std::cout << "Please, enter your name: ";
  std::cin.getline (name,256);

  std::cout << "Please, enter your favourite movie: ";
  std::cin.getline (title,256);

  std::cout << name << "'s favourite movie is " << title;

  return 0;
}

For more information on buffer flushing, I found a decent SO question on it: What does flushing the buffer mean?

jaypb
  • 1,544
  • 10
  • 23