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

如何在C++中通过ifstream根据图书索引获取对应页码

问题描述

我有一个存储3本图书页码数据的TXT文件,格式如下:

0 3
1 57
2 173

其中0、1、2为图书索引,需与对应页码关联。我正在编写C++程序用于快速修改该数据以适配网站,需求是接收用户输入的图书索引,输出对应的页码。

当前代码如下:

std::ifstream file("C:\\Users\\Robed\\OneDrive\\Documents\\Judah.site\\book_keep.txt");

if (!file.is_open())
{
    std::cerr << "File could not be opened, make sure path is right!" << std::endl;
    return false;
}

std::string line;


while (getline(file, line)) {
    std::cout << line << std::endl;
}

int inputBookIndex;
std::cout << "Input book index to change page number of: ";
std::cin >> inputBookIndex;

if (inputBookIndex < 0)
{
    std::cout << "Invalid Book Index!" << std::endl;
    return false;
}

file.close();

return true;

目前已实现文件读取功能,但无法建立图书索引与页码的关联,想要实现如下交互效果:

Enter Book Index: 0
Page Number: 3
解决方案

要实现索引与页码的关联,核心是用容器存储两者的映射关系,具体实现步骤如下:

  1. 引入映射容器:使用std::unordered_map<int, int>存储索引(键)和页码(值)的对应关系,保证高效查找。
  2. 解析文件行数据:读取每行后,拆分出整数类型的索引和页码,存入容器。
  3. 处理用户输入:根据输入的索引在容器中查找对应页码,存在则输出,否则提示无效。

修改后的完整代码:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <unordered_map>

int main() {
    std::unordered_map<int, int> bookPageMap;
    std::ifstream file("C:\\Users\\Robed\\OneDrive\\Documents\\Judah.site\\book_keep.txt");

    if (!file.is_open())
    {
        std::cerr << "File could not be opened, make sure path is right!" << std::endl;
        return 1;
    }

    std::string line;
    while (getline(file, line)) {
        std::istringstream iss(line);
        int index, page;
        // 解析每行的索引和页码并存入映射
        if (iss >> index >> page) {
            bookPageMap[index] = page;
        }
    }
    file.close();

    int inputBookIndex;
    std::cout << "Enter Book Index: ";
    std::cin >> inputBookIndex;

    // 检查索引合法性
    if (inputBookIndex < 0)
    {
        std::cout << "Invalid Book Index!" << std::endl;
        return 1;
    }

    // 查找并输出对应页码
    auto it = bookPageMap.find(inputBookIndex);
    if (it != bookPageMap.end()) {
        std::cout << "Page Number: " << it->second << std::endl;
    } else {
        std::cout << "Book Index not found!" << std::endl;
        return 1;
    }

    return 0;
}

关键改动说明

  • 容器选择:std::unordered_map提供平均O(1)的查找效率,适合快速定位索引对应的页码。
  • 行解析逻辑:用std::istringstream将每行字符串拆分为整数,避免手动处理字符串拆分的繁琐。
  • 路径修正:原代码中的路径单反斜杠\需转义为\\,否则会被识别为转义字符导致路径错误。
  • 查找逻辑:通过find()方法判断索引是否存在,避免直接访问不存在的键引发未定义行为。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 19:51:01