【问题标题】:Why the result differs when I press enter at the end of a sentence? [closed]为什么我在句末按回车结果不同? [关闭]
【发布时间】:2016-11-05 10:13:02
【问题描述】:

这是我的第一个程序

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

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

但是,另一个程序中的代码表现不同:

#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,它会等待我输入更多数据而不是显示结果。

你能给我解释一下吗?

【问题讨论】:

  • 不确定 MSVC (Visual Studio),但其他编译器 are capable 会告诉您有问题。通常值得多试几次才能看到警告。

标签: c++ cin enter


【解决方案1】:

删除while 循环后的分号。事实上,它强制循环没有主体,这意味着它只会在cin 上永远循环。更好的是,使用大括号来分隔正文:

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

【讨论】:

    猜你喜欢
    • 2014-06-29
    • 1970-01-01
    • 2010-11-26
    • 2012-07-28
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    相关资源
    最近更新 更多