-2

The following code is made:

#include <string>
#include <iostream>
using namespace std;

int main() {
 string s;

 while(true) {
 cin >> s;
 cout << "type : " << s << endl;
 }
}

The output of the console is:

INPUT: usa americ england gana

OUTPUT:

type : usa
type : americ
type : england 
type : gana

INPUT: hello world

OUTPUT:

type : hello
type : world

Whenever I type "usa americ englend gana" and then enter, it displays each string input via cin in the while block.

Is there any reason for this? How is the "stream buffered"?

How could I make it so that whenever multiple strings are input via cin, there is no separation made by whitespaces? Is there any particular function or answer to this problem?

Sneftel
  • 34,359
  • 11
  • 60
  • 94
user8282818
  • 91
  • 1
  • 8

1 Answers1

2

One call to operator>> of std::cin reads only up to the first whitespace. When you input 4 words in one line, your std::cin reads the first word, accepts it, and execution continues. But the remaining 3 words are still waiting in the input stream to be read, and they will be read upon next call of operator >>.

So, to illustrate what happens, here's an example:

Input stream content: [nothing]
//(type usa americ england gana)
Input stream content: usa americ england gana
//cin >> s;
s == "usa"
Input stream content: americ england gana
//cin >> s;
s == "americ";
Input stream content: england gana
//etc.

You may want to try std::getline to read whole lines instead. Just don't mix std::cin and std::getline.

while(true) {
    std::getline(std::cin, s)
    cout << "type : " << endl;
}
Yksisarvinen
  • 13,037
  • 1
  • 18
  • 42
  • Thank you for the answer. I get understood. I have another question! If I put enter key, "usa americ england gana" goes to buffer. right?? So I think enter key' role is sending "usa americ england gana" to buffer. therefore, I think cin works when enter key is typed. In that next roop case, how cin works without my enter key?? – user8282818 Dec 13 '18 at 14:44
  • ***how cin works without my enter key??*** It does not. Here is more info: https://stackoverflow.com/questions/421860/capture-characters-from-standard-input-without-waiting-for-enter-to-be-pressed and https://stackoverflow.com/questions/15209370/how-do-i-input-variables-using-cin-without-creating-a-new-line – drescherjm Dec 13 '18 at 18:28