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

C++技术问题:统计文本文件中排除指定前缀行的G/C字符数量

解决C++统计文本G/C字符并排除指定前缀行的问题

需求说明

统计文本文件中G、C(大小写均算)的出现次数,但必须排除以“*”开头的行。

示例文本

*metadata information
atgctaatgcaggtcagtcagtcagtcatgcg
atgcagtcagtcactgactgactgactgaata
*metadata information
atgtagcagctagtcagtcagtcagcatatat
gatcgactagctgactgacgtactgactgaat

现有错误代码

char Z;
long GC=0;
string Line;

while(getline(InFile, Line)) 
{
    if(Line[0]=='*')
    {
        InFile.get(Z);
        while(InFile.get(Z))
        {
            if(Z=='G' || Z=='C' || Z=='g' || Z=='c')
            {
                ++GC;
            } 
        } 
    }
}

问题分析

这段代码逻辑完全搞反了:

  • 它只对以“”开头的行做处理,而且用getline读行后又调用get(Z),会跳过后续行的正常读取,直接读到文件末尾,完全忽略了非“”开头的目标行。
  • 没有考虑空行的情况,如果某行是空的,Line[0]会导致越界访问。

正确实现代码

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

using namespace std;

int main() {
    ifstream InFile("your_file.txt"); // 替换成你的目标文件名
    long GC = 0;
    string Line;

    while (getline(InFile, Line)) {
        // 跳过空行和以*开头的行
        if (Line.empty() || Line[0] == '*') {
            continue;
        }
        // 遍历当前行的每个字符统计G/C
        for (char c : Line) {
            char lower_c = tolower(static_cast<unsigned char>(c));
            if (lower_c == 'g' || lower_c == 'c') {
                ++GC;
            }
        }
    }

    cout << "G和C的总出现次数:" << GC << endl;
    return 0;
}

代码说明

  1. 用getline逐行读取文件,先判断行是否为空或者以“*”开头,满足条件直接跳过。
  2. 对有效行,用范围for循环遍历每个字符,通过tolower统一转小写,简化大小写判断逻辑。
  3. 避免了原代码中读取行后又单独读字符的混乱逻辑,保证每行都被正确处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 02:55:39