Help with C++ const char * with class member functions!
Hello, I am trying to count the number of times that "Ni" occurs in the string "Ni nI NI nI Ni". However, I can't get my code to work. Any help that I could get as soon as possible would be wonderful. Keep in mind that I need to keep the class MyClass, and the getNiCount function within the public section of that class. Also, I need to have const char *szTestString1 = "Ni nI NI nI Ni"; in my main function.
// classes example
#include <iostream>
using namespace std;
class MyClass {
public:
int getNiCount(const char *phrase)
{
int index = 0;
int num_occurences = 0;
while(index != 14){
if(phrase[index] == 'N' && phrase[index+1] == 'i')
{
num_occurences = num_occurences + 1;
}
else
{
index++;
}
}
return num_occurences;
};
int main () {
MyClass phrase1;
const char *szTestString1 = "Ni nI NI nI Ni";
cout << phrase1.getNiCount(szTestString1) << endl;
return 0;
}
Re: Help with C++ const char * with class member functions!
Let me guess, it goes into an infinite loop.
Use your debugger and step through the code.
In fact, just step through the code in your head and determine what is going to happen.
Re: Help with C++ const char * with class member functions!
Why 14? You would do better to determine the length dynamically, perhaps with strlen(), rather than hardcoding it.
Aside from that I can see no reason to get a class involved in this task.