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

C++读取逗号分隔TXT文件内容并存储到数组中求助

读取用户信息到数组的实现方案

以下是用C++实现读取TXT文件内容到name[]和user_Id[]两个数组的方案,同时包含用户输入校验的逻辑:

核心思路

  1. 先统计文件有效行数,确定数组的大小
  2. 动态分配字符串数组,避免固定大小的局限性
  3. 逐行读取文件内容,按逗号分割并去除前后多余空格
  4. 遍历数组实现用户信息的存在性校验

完整代码实现

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <cctype>

// 去除字符串前后空格的辅助函数
std::string trim(const std::string& s) {
    auto start = s.begin();
    while (start != s.end() && std::isspace(*start)) {
        start++;
    }
    auto end = s.end();
    do {
        end--;
    } while (std::distance(start, end) > 0 && std::isspace(*end));
    return std::string(start, end + 1);
}

int main() {
    std::ifstream file("users.txt");
    if (!file.is_open()) {
        std::cerr << "无法打开文件" << std::endl;
        return 1;
    }

    // 统计文件有效行数
    int lineCount = 0;
    std::string line;
    while (std::getline(file, line)) {
        if (!line.empty()) {
            lineCount++;
        }
    }
    file.close();

    // 动态分配两个字符串数组
    std::string* name = new std::string[lineCount];
    std::string* user_Id = new std::string[lineCount];

    // 重新打开文件读取内容
    file.open("users.txt");
    int index = 0;
    while (std::getline(file, line)) {
        if (line.empty()) continue;

        size_t commaPos = line.find(',');
        if (commaPos != std::string::npos) {
            // 分割字符串并去除前后空格
            name[index] = trim(line.substr(0, commaPos));
            user_Id[index] = trim(line.substr(commaPos + 1));
            index++;
        }
    }
    file.close();

    // 示例:输出读取到的所有用户信息
    std::cout << "读取到的用户信息:\n";
    for (int i = 0; i < lineCount; i++) {
        std::cout << "用户名:" << name[i] << " | 用户ID:" << user_Id[i] << "\n";
    }

    // 校验用户输入的用户名是否存在
    std::string inputName;
    std::cout << "\n请输入要校验的用户名:";
    std::cin >> inputName;

    bool isExist = false;
    for (int i = 0; i < lineCount; i++) {
        if (name[i] == inputName) {
            isExist = true;
            std::cout << "用户名「" << inputName << "」已存在,对应ID:" << user_Id[i] << "\n";
            break;
        }
    }
    if (!isExist) {
        std::cout << "用户名「" << inputName << "」不存在于系统中\n";
    }

    // 释放动态分配的内存,避免内存泄漏
    delete[] name;
    delete[] user_Id;

    return 0;
}

关键说明

  • 动态数组:通过提前统计行数来分配数组大小,比固定大小数组更灵活,适配文件内容的变化
  • 空格处理:trim函数会去除用户名和ID前后的空格,确保存储的内容无冗余字符,避免对比时出现错误
  • 校验逻辑:直接遍历数组对比字符串,实现简单高效,满足你对用户输入的校验需求
  • 内存管理:使用delete[]释放动态分配的数组,避免内存泄漏问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 00:45:13