Search code examples
c++cinenter

Why the result differs when I press enter at the end of a sentence?


Here is my first program

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

int main()
{
    int a;
    string s;
    double d;
    while(cin >> a >> s >> d)
        cout << a << s << d;
    return 0;
}

When I input some simple data and press Enter , the result is shown immediately:

image

However, the code in another program behaves differently:

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

struct Sales_data {
    string bookNo;
    unsigned units_sold = 0;
    double price = 0.0;
    void Print();
};

void Sales_data::Print(){//print every record of the Sales_data
    cout << "The bookNo of the book is " << bookNo << endl;
    cout << "The units_sold of the book is " << units_sold << endl;
    cout << "The price of the book is " << price << endl;
}

int main()
{
    Sales_data book;
    while(cin >> book.bookNo >> book.units_sold >> book.price);
        book.Print();
    return 0;
}

When I run this code, input some data, and press Enter, it waits for me to input more data rather than show the result.

image

Could you explain this to me?


Solution

  • Remove the semicolon after the while loop. As it is, it forces the loop to have no body, which means it just cycles over the cin forever. Even better, use braces to delimit the body:

    while(cin >> book.bookNo >> book.units_sold >> book.price) {
        book.Print();
    }