正在跳过的字符串类的字符计数函数
Function counting characters of a string class being skipped?
我试图计算字符串类中的字符数,但由于某种原因,程序完全跳过了我的函数。这只是主程序的测试代码,它仍然给了我相同的结果。为什么计数器功能被跳过了?
#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语句会更简洁。
相关文章:
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 将字符随机转换为大写的函数
- 固有构造函数的字符和访问级别
- constexpr 函数获取常量字符*
- 将字符缓冲区强制转换为函数指针
- 函数签名与调用的函数不匹配,常量字符[]和字符*之间的区别?
- 将字符串数组传递给接受常量字符**的函数
- 在函数中返回无符号字符数组,但不返回指针
- 如何返回实际值(在我的例子中是无符号字符数组)而不是来自 C++ 函数的指针?
- 在函数 strcpy() 中访问字符数组时出现分段错误
- 如何循环访问 cpp 中的函数返回的字符指针数组
- 自定义 std::fstream,std::filebuf 的溢出和下溢函数未为每个字符调用
- 如何在字符函数中选择某些字符?
- 使用排序函数 c++ 对字符数组进行排序
- 字符串到字符* 函数
- 空间字符函数
- 在字符函数中传递字符值时出现奇怪的错误
- 正在更新字符* 函数C++
- 反转字符函数,但不会输出