当我在句子末尾按Enter键时为什么结果不同?

时间:2016-07-03 16:14:06

标签: c++ cin enter

这是我的第一个程序

#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;
}

当我输入一些简单数据并按 Enter 时,结果会立即显示:

image

但是,另一个程序中的代码行为不同:

#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;
}

当我运行此代码,输入一些数据,然后按 Enter 时,它等待我输入更多数据而不是显示结果。

image

你能解释一下吗?

1 个答案:

答案 0 :(得分:3)

while循环后删除分号。实际上,它强制循环没有主体,这意味着它只是永远地遍历cin。更好的是,使用大括号来划分身体:

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