Loop Tutorial Example

Hello, its my third day coding
I use codeblock

In your tutorial it says this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 // echo machine
#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string str;
  do {
    cout << "Enter text: ";
    getline (cin,str);
    cout << "You entered: " << str << '\n';
  } while (str != "goodbye");
}


When I run that the outcome is:

Line 1: Enter text: You entered:
Line 2: Enter text: hey
Line 3: You entered: hey

So after the first line I can enter text and it repeats it just fine.

My question is why does that first line appear?
After that it works fine.

I have had a similar problem with other string and getline examples..
Last edited on
Line 1: Enter text: You entered:

I don't see any reason as to why Line 1 would look like that, and it doesnt when I run it both on visual studio and on cpp.sh - http://cpp.sh/8sng6

I get -

Line 1: Enter Text:
Then you can enter.
Line 2: You entered: blablabla
Line 3: Enter Text:

And it repeats like that. Are you sure you are running this exact piece of code that you showed us. Because the only reason I can think of which would cause what you are saying is happening, is if you are switching between std::cin >> and std::getline, because you'll have to flush then.
Last edited on
Using both cin and getline was the problem. It was in a document where there was some other code that used cin.

Thank you!
Topic archived. No new replies allowed.