0

Can someone help me with what I've done wrong with the character count function?

it should be returning

abcdefghijklmnopqrstuvwxyz ABVDEFGHIJKLMNOPQRSTUVWXYZ as 52 but it is coming back as 136088???

#include <iostream>
#include <cctype>

using namespace std;

const int STRINGSIZE = 100;

void getString(char string[]);
void reverseCase(char string[]);
int numGraph(char string[]);


int main()
{
   char string[STRINGSIZE];
   int count;

   getString(string);
   cout << "Entered string => " << string << "\n";

   count = numGraph(string);
   cout << "Number of graphic characters in string = " << count << "\n";

   reverseCase(string);
   cout << "Reverse case   => " << string << "\n";

   return 0;
}

void reverseCase(char string[])
{
   /****************************************************************\
      Reverse the case of all alphabetic characters in the string.
      That is, all upper case characters become lower case and 
      all lower case become upper case.
   \****************************************************************/

   int j=0;
   char *c;

   while (string[j])
   {
      c = (&string[j]);
      if (isupper(*c)) *c = tolower(*c);
      else *c = toupper(*c);
      j++;
   }
}

int numGraph(char string[])
{
   /***************************************************************\
      Calculate the number of printable graphic characters in the
      string.
   \***************************************************************/

   int i, count;

   for (i=0; string[i] != '\0'; i++)
   {
      if (isgraph(string[i])) count++;
   }
   return count; 
}

void getString(char string[])
{
   /************************************************************\
      
      Use getline function to get entire line of text up to

      maximum of STRINGSIZE-1 chars in length
   
   \************************************************************/
   
   cout << "Please enter a string to process\n";

   cin.getline(string, STRINGSIZE);
}
2
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by Narue
0

>int i, count;
You're not initializing count to 0, so when you increment, it starts at whatever garbage value was already in memory.

0

I just realised I needed to set in main as well.

Thanks

0

You do set it in main: count = numGraph(string); . The problem is that in numGraph, the count begins at who knows where because you never set the value before incrementing and then returning it.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.