开发者

Function counting characters of a string class being skipped?

I was trying to count the number of characters in a string class but for some reason the program is skipping over my function completely. This is just the test code from the main program, it still was giving me the same results. How come the counter function is skipped over?

#include <iostream>
#include <string&g开发者_JAVA百科t;

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 << "\n\nAfter:\n"
             << "A: " << a << endl
             << "T: " << t << endl
             << "C: " << c << endl
             << "G: " << g << endl;
    }

    system("pause");

    return 0;
}


You're applying operator ++ the wrong way. It should be:

    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)++;
    }


You've got a priority problem between the ++ and * operators. You are incrementing the pointer address, not the value. (*a_count)++; would be correct.


You may find it easier to use reference parameters for the counts instead, since you don't actually need to do any pointer arithetic. ie:

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

And, yes a switch statement would be neater.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜