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

C++读取TXT文件逐行校验问题:仅处理最后一行求助

问题分析与修复方案

你的代码核心问题是所有校验逻辑都写在了读取文件的while循环外部:

  • while循环每次读取一行到input变量里,但仅执行打印操作,未处理校验逻辑
  • 循环结束后,input仅保留最后一行的内容,所以后续的长度检查、权重计算只会作用在最后一行上

修正后的核心代码

把长度校验、权重计算等逻辑全部移到while循环内部,实现每读取一行就立即处理一行:

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

using namespace std;

int main()
{
    stringstream cs;
    stringstream ss;
    stringstream rr;
    stringstream mm;
    string input;
    
    std::ifstream File ("idnumbers.txt");
    if (File.is_open())
    {
        while (std::getline(File, input))
        {  
            cout << "处理ID: " << input << '\n';
            
            // 移到循环内:检查当前行ID长度
            if (input.length() != 18)
            {
                cout << "ID长度错误,跳过该行\n";
                continue; // 跳过当前错误行,继续处理下一行
            }   

            int orderedSet[] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
            string index = "10X98765432";

            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += (input[i] - '0') * orderedSet[i];
            }
            
            // 继续执行你的模11运算与校验逻辑,示例如下:
            int remainder = sum % 11;
            char checkDigit = index[remainder];
            if (checkDigit == input[17])
            {
                cout << "ID校验通过\n";
            }
            else
            {
                cout << "ID校验失败,正确校验位应为: " << checkDigit << '\n';
            }
        }
        File.close();
    }
    else
    {
        cout << "无法打开文件\n";
        return 1;
    }

    return 0;
}

关键修改点

  • 将长度检查、权重求和、模11校验等所有行处理逻辑,全部放入while (getline(File, input))的循环体内
  • 把原来的return 1改成continue,避免遇到错误行就直接终止程序,保证后续行能继续处理
  • 补充文件打开失败的分支处理,避免程序静默出错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 23:24:56