0

So basically I was making a chat app and then I came across to a bug i couldnt fix. for purpose of not leaking my source code here is an example of it:

#include<iostream>
using namespace std;

int main()
{
    while (true) {
        string lol;
        cout << "you say >> ";
        cin >> lol;
    }
    return 0;
}

so the bug is when you type a space in cin like you type: "hi lol" it prints "you say >>" twice and the more space you put the more "you say >>" repeats I really dont understand why this is happening. can soemone help me?

Spixa
  • 25
  • 6
  • See [How to read a complete line from the user using cin?](https://stackoverflow.com/questions/5455802/how-to-read-a-complete-line-from-the-user-using-cin) – dxiv May 06 '20 at 19:21
  • `cin >> lol` is skipping all white space, compare https://en.cppreference.com/w/cpp/string/basic_string/operator_ltltgtgt. – Werner Henze May 06 '20 at 19:21
  • So, basically, have you looked at [this question](https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces) that explains how to treat whitespace in `cin()`? – Mihai May 06 '20 at 19:24
  • FYI, you declare a new instance of the string at the top of the while loop and don't every print the value of `lol`. – Thomas Matthews May 06 '20 at 19:34
  • thanks guys i fixed it: ```#include using namespace std; int main() { while (true) { static char lol[128]; cout << "you say >> "; cin.getline(lol,256); cout << lol << endl;; } return 0; }``` – Spixa May 06 '20 at 19:56

1 Answers1

3

That's no bug, that's the way it works.

The operator>>() for std::string separates by whitespace, so you effectively get one word at a time.

If you'd like to read an entire line, use std::getline().

Fred Larson
  • 60,987
  • 18
  • 112
  • 174