gpt4 book ai didi

C++ Primer 第 5 版,练习 1.23 无输出

转载 作者:行者123 更新时间:2023-11-30 04:55:32 27 4
gpt4 key购买 nike

我正在使用 C++ 入门自学 C++,并且在练习 1.23 上被难住了两天。这是问题所在:

Exercises Section 1.5.2

Exercise 1.23: Write a program that reads several transactions and counts how many transactions occur for each ISBN.

Exercise 1.24: Test the previous program by giving multiple transactions representing multiple ISBNs. The records for each ISBN should be grouped together.

我应该使用一个名为“Sales_item”的类来提供此信息,该类接受 ISBN、项目数量和销售价格(例如 <ISBN> 4 24.99)的输入。它还支持以下操作:

我试着用下面的代码做第一个练习:

#include <iostream>
#include "Sales_item.h"

int main()
{
int cnt = 0;
Sales_item item1, item2, item3, item4;
//Verify we have data from the infile
if (std::cin >> item1) {
cnt = 1;
//read the rest of the transactions and add to cnt for each
while (std::cin >> item2 >> item3 >> item4) {
cnt++;
}
}
else {
std::cout << item1.isbn() << " has a total of " << cnt <<
" transactions." << std::endl;
}
return 0;
}

我的想法是,每次将交易传递给标准输入时,while 循环应该递增 cnt 变量,然后在到达列表末尾时输出反射(reflect)交易数量的语句,但我什么也没得到为输出。关于这应该如何工作,我的推理/逻辑是否错误?

最佳答案

operator>>cin 这样的 iostreams 返回流本身,这就是你如何链接它们。所以你的 while 循环中的测试总是非零的,因此永远不会退出。

关于C++ Primer 第 5 版,练习 1.23 无输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52980721/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com