You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++如何筛选存储并输出类型为childrensbook的图书

C++实现筛选输出儿童类图书方案

需求说明

需要从录入的图书信息中,筛选出booktype为childrensbook的图书并统一输出名称:

  • 类型为drama的图书tower不符合筛选要求
  • 类型为childrensbook的flower、sun属于需要输出的儿童图书
    示例数据结构:
bookname : tower
booktype : drama
bookname : flower
booktype : childrensbook
bookname : sun
booktype : childrensbook
...

预期输出结果:

  • flower
  • sun

原代码问题说明

现有代码已经完成循环录入、类型匹配的基础框架,但存在3个影响功能的问题:

  • 数组赋值误用相等比较运算符==,name2[i] == book1.name、type2[i] == book1.type两行代码不会把录入的信息存入数组,需要改成赋值运算符=
  • 头文件引用错误,使用C++的string类需要引入<string>头文件,原代码引入的<string.h>是C语言字符串处理头文件
  • 类型匹配分支缺少符合条件图书的存储逻辑,没有录入完成后的统一输出步骤

修正后可运行代码

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

class Books
{
public:
    string name;
    string type;
    void getdetails() {
        cout <<"enter book's name :  ";
        cin >> name;
        cout <<"enter book's type :  ";
        cin >> type;
        cout << endl;
    }
};

int main() {
    // 存储全量录入图书信息的数组
    string name2[19];
    string type2[19];
    // 存储筛选后儿童图书的结果数组
    string childrenBooks[19];
    const string targetType = "childrensbook";
    Books book1;
    // 记录符合筛选条件的图书总数
    int matchCount = 0;

    for (int i=0;i<5;i++) 
    {
        cout << "Book " << (i+1) << " info : " << endl;
        book1.getdetails();
        // 修正原代码双等号问题,使用单等号完成赋值
        name2[i] = book1.name;
        type2[i] = book1.type;
    
        if(targetType == book1.type)
        {
            // 类型匹配成功时,将书名存入结果数组,计数自增
            childrenBooks[matchCount] = book1.name;
            matchCount++;
        }
    }

    // 全量录入完成后统一输出结果
    cout << "待输出的儿童图书为:" << endl;
    for (int j = 0; j < matchCount; j++) {
        cout << "- " << childrenBooks[j] << endl;
    }

    return 0;
}

核心逻辑说明

  • 新增childrenBooks数组专门存储筛选通过的儿童图书名称,用matchCount变量记录符合条件的图书总数,避免输出无效空值
  • 修正运算符、头文件的基础语法错误,保证录入的图书信息可以正常存入数组
  • 所有图书录入流程结束后,根据matchCount的数值遍历结果数组,按要求格式输出所有符合条件的图书名称

内容的提问来源于stack exchange,提问作者yami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 18:27:25