理解C ++中的cin行为

时间:2016-06-18 10:08:25

标签: c++

我正在学习C ++并遇到了这个问题。有人可以解释为什么我的解决方案不起作用吗?这是我的代码和问题:

struct Pizza {
    char company[30];
    double size;
    int weight;
};

int main() {
    Pizza *test = new Pizza;

    cout << "Enter size: ";

    //from Internet, works
    (cin >> test->size).get();

    //my idea, doesnt work, why ?
    cin >> test->size;

    cout << "Enter company: ";
    cin.get(test->company, 30);
    cout << "Enter weight: ";
    cin >> test->weight;
    cout << "Company: " << test->company<< " \nSize: "
        << test->size << " \nWeight: " << test->weight << endl;
    delete test;
    cin.get();
    cin.get();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

cin >> test->size;完美无缺:)

认为的原因是因为流中仍会有新的行\n。之后,当您cin.get(test->company, 30);时,它会读取流并立即返回,因为它会读取新行。

但是当你拨打std::cin.get()时,它会读取一个字符,即新行,并将其从流中丢弃,因此该流为空,您可以输入公司名称。

您也可以在之后调用它:

cin >> test.size();
cin.get();