C++/cstring

Advertisement


Question
writ a function to count the number of occurrences of a letter in a c string?
this is my trying :-)
#include <iostream>
#include <string>
int countVowels(char str[], char k);
using namespace std;
int main ()
{
  char str[] = " I love my stuff esspecially my glass, bag and watch";
  int k;
  char a;
  cout<<"enter the letter that you want to count";
  cin>> a;
   countVowels(str, k);
  return 0;
}
int countVowels(char str[], char k)
{
   int count = 0, i = 0;
   while (str[k] != '\0')
   {
     for (i=0; countVowels[i]='\0'; i++)
     {
         if (str[k] == 'a')
       {
         count++;
         k++;
       }
     }
   }
   return count;
}


Answer
Hi,

I have some comments:

1) You have cin >> a.  Then you call count with k.  Call count with a:

count(str,a);

2) Function count has some problems.  You don't need a while and for.

Your version uses k for the index - you want to use k just to compare:

int countVowels(char str[], char k)
{
  int count = 0, i;
  for (i=0; str[i]!='\0'; i++)
     {
     if (str[i] == k)
        count++;
     }
  return count;
}

Here's another way:

int countVowels(char *str, char k)
{
  int count = 0;
  while(*str!='\0')
     {
     if (*str++ == k)
        count++;
     }
  return count;
}

Bill

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Bill A

Expertise

I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.

Experience

I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Publications
Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

Education/Credentials
BS Computer Engineering

©2016 About.com. All rights reserved.