正在跳过的字符串类的字符计数函数

Function counting characters of a string class being skipped?

本文关键字:字符 函数 字符串      更新时间:2023-10-16

我试图计算字符串类中的字符数,但由于某种原因,程序完全跳过了我的函数。这只是主程序的测试代码,它仍然给了我相同的结果。为什么计数器功能被跳过了?

#include <iostream>
#include <string>
using namespace std;
void prompt(string& dna)
{
    cout << "Input: ";
    getline(cin, dna);
}
void counter(const string DNA,
                 int* a_count, int* t_count, int* c_count, int* g_count)
{
    for (int i = 0; i < DNA.size(); i++)
    {
        if (DNA.at(i) == 'a')
        {
            *a_count++;
        }
        else if (DNA.at(i) == 't')
        {
            *t_count++;
        }
        else if (DNA.at(i) == 'c')
        {
            *c_count++;
        }
        else if (DNA.at(i) == 'g')
        {
            *g_count++;
        }
    }
}
int main()
{
    string dna;
    int a = 0;
    int t = 0;
    int c = 0;
    int g = 0;
    prompt(dna);
    if (! dna.empty())
    {
        cout << "Before:n"
             << "A: " << a << endl
             << "T: " << t << endl
             << "C: " << c << endl
             << "G: " << g << endl;
        counter(dna, &a, &t, &c, &g);
        cout << "nnAfter:n"
             << "A: " << a << endl
             << "T: " << t << endl
             << "C: " << c << endl
             << "G: " << g << endl;
    }
    system("pause");
    return 0;
}

您应用运算符++的方式不对。应该是:

    if (DNA.at(i) == 'a')
    {
        (*a_count)++;
    }
    else if (DNA.at(i) == 't')
    {
        (*t_count)++;
    }
    else if (DNA.at(i) == 'c')
    {
        (*c_count)++;
    }
    else if (DNA.at(i) == 'g')
    {
        (*g_count)++;
    }

++和*运算符之间存在优先级问题。您正在递增指针地址,而不是值。CCD_ 1将是正确的。

您可能会发现使用计数的引用参数更容易,因为您实际上不需要进行任何指针修复。即:

void counter(const string DNA, int& a_count, int& t_count, int& c_count, int& g_count)

是的,switch语句会更简洁。