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

已读取行首字符后如何读取文件整行整数?C++程序问题

C++读取文件计算整数总和问题解决

问题说明

需求:编写C++程序读取文件,计算其中所有整数的总和,文件中每行仅包含字符串或整数,二者不会同时存在。
当前实现思路:逐字符读取每行内容,若字符ASCII码在48-57之间,使用>>运算符提取整数,直至文件结束。
遇到的问题:读取行首为数字的内容时,会丢失该整数的第一位;尝试用seekg()调整文件指针但未奏效。

原代码

//A program that read file and calculate sum of numbers in file 
#include <iostream>
#include <fstream>
#include <string.h>
int main ()
{

    // decalre File path string to store path of file
    std::string FilePath;
    //recive from a user 
    std::cin>>FilePath;
    //FilePath = "\""+ FilePath + "\"";
    //mine guide
    std::cout<<FilePath;

    //declare Infile object of input stream for only read file
    std::ifstream InFile ;
    //open file
    InFile.open(FilePath.c_str() , std::ios::in);
    //inser if condition if file does not opened
    if(!InFile)
    {
        std::cerr<<"can not open file ";
        return 1;
    }
    //what the hell is that  i forgot 
    std::string FileString ;
    //decalre char type check char to check the line start with number or charater
    char checkChar {};
    //declare NUminFilie to read Nums in file
    int  NumInFile{};
    // declare for calcualte sum of Nums in File
    int SumOfNumInFile{};
    //declare In vain string to go to next line in file
    std::string InVainString ;
    int counter = 0;
    std::cout<<"befot while\n";
    // insert a boolian variable falg  to avoid back cursor if number is in begening of file because 
    bool flagNotAtFirstOfFile = false;
    while (InFile.get(checkChar))
    {
    
    
    
        std::cout<<"get\n";
        std::cout<<(int)checkChar<<std::endl;
        if((((int)checkChar>=49)&&((int)checkChar<=57)))
        {
            std::cout<<"if char is done";
            if(flagNotAtFirstOfFile)
            {   std::cout<<"   seekg is done  "<<std::endl;
                InFile.seekg(,std::ios::cur);

            }
            else 
            {
                InFile.seekg(0,std::ios::beg);
                flagNotAtFirstOfFile = true;

            }
            InFile>>NumInFile;
            std::cout<<NumInFile<<std::endl;
            SumOfNumInFile+= NumInFile;



        }
        // insert if condition to if checkChar read space character between 2 line number continue and do not read line 
        else if ((int)checkChar ==10)
        {
            continue ;
        }
        else
        {
            InFile.seekg(0,std::ios::cur);
            std::getline(InFile,InVainString);
            std::cout<<"getline :"<<InVainString<<std::endl;
        }

        //std::cout<<"getline :"<<InVainString<<std::endl;
        //InFile.peek();
        

    }
    std::cout<<SumOfNumInFile;
    return 0;

}

问题原因

  1. 指针偏移导致丢位:用InFile.get(checkChar)读取了行首的第一个数字字符后,文件指针已经移动到下一个字符,此时再用>>读取整数,会从第二个字符开始读,自然丢失第一位。
  2. seekg使用错误:代码中InFile.seekg(,std::ios::cur)是语法错误,缺少偏移量参数;即使参数正确,这种逐字符判断+指针回退的逻辑本身就容易出错,逻辑冗余且复杂。
  3. 忽略了'0'的判断:原代码判断数字的条件是checkChar>=49&&checkChar<=57,漏掉了ASCII码为48的字符'0',导致以0开头的整数直接被当成字符串处理。

修正方案

既然每行要么是纯整数要么是纯字符串,直接逐行读取内容,然后尝试将每行字符串转换为整数:

  • 使用std::getline逐行读取文件内容
  • 用std::istringstream尝试将字符串解析为整数,解析成功则累加,失败则跳过该行

这种方法逻辑简单,避免了文件指针操作的复杂问题,同时能正确处理所有合法整数(包括以0开头的情况)。

修正后完整代码

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

int main() {
    std::string FilePath;
    std::cout << "请输入文件路径:";
    std::cin >> FilePath;

    std::ifstream InFile(FilePath);
    if (!InFile.is_open()) {
        std::cerr << "无法打开文件!" << std::endl;
        return 1;
    }

    int SumOfNumInFile = 0;
    std::string line;

    while (std::getline(InFile, line)) {
        std::istringstream iss(line);
        int num;
        // 尝试将字符串解析为整数,成功则累加
        if (iss >> num && iss.eof()) { // iss.eof()确保整行都是整数,没有多余字符
            SumOfNumInFile += num;
        }
        // 解析失败则直接跳过该行
    }

    std::cout << "文件中所有整数的总和为:" << SumOfNumInFile << std::endl;
    InFile.close();
    return 0;
}

代码说明

  1. 逐行读取:用std::getline(InFile, line)读取每行内容,避免了逐字符处理的繁琐。
  2. 整数解析判断:std::istringstream将字符串转为输入流,iss >> num尝试读取整数,iss.eof()确保整行内容都被解析为整数(符合需求中每行纯整数或纯字符串的设定)。
  3. 错误处理:打开文件时判断是否成功,确保程序健壮性。

测试结果

使用示例输入文件:

232300
675
khobi
chekhabar
233
34340
hjhkjh
6757
876876
hehehhe
1100

运行程序后,计算的总和为:232300 + 675 + 233 + 34340 + 6757 + 876876 + 1100 = 1152281,结果正确。

内容的提问来源于stack exchange,提问作者Mohammad Erfan Noori

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 18:39:57