I am writing a program that will take a sentence and find out how many of one character (like how many h's) is in the sentence. I have started what I think works and got the program to work once but after the one time I cant get it to work again. Any help on how to fix my program would be greatly appreciated.

#include <stdafx.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h> 


int main( void )
{ 
   char text[ 3 ][ 80 ]; 
   char search;          
   char *searchPtr;      
   int count = 0;       
   int i;               
   int k;                
   
   printf( "Enter two lines of text:\n");
   for ( i = 0; i < 2; i++ ) {
      gets( &text[ i ][ i ] );
    
   }
   for ( i = 0; i <= 2; i++ ) {
      
   }
   for ( k = 0; text[ i ][ k ] != '\0'; k++ ){
       text[ i ][ k ] = tolower (text[ i ][ k ] );
      } 

    
   printf( "\nEnter a search character: "); 
   scanf( "%c", &search );

   for ( i = 0; i <= 2; i++ ) { 


      searchPtr = &text[ i ][ 0 ];
      
   }
   while ( searchPtr = strchr( searchPtr, search ) ) {
         count++; 
         searchPtr++;
   }

	  
	  
   
   printf( "The total occurrences of '%c' in the text is %d\n",
          search, count );

   return 0;  
   }

Edited 6 Years Ago by Chocolatemoon: n/a

i have marked the places where i have made changes:-

#include <stdafx.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h> 


int main( void )
{ 
   char text[ 3 ][ 100 ]; 
   char search;          
   char *searchPtr;      
   int count = 0;       
   int i;               
   int k;                
   
   printf( "Enter two lines of text:\n");
   for ( i = 0; i < 2; i++ ) {
      fgets(&text[ i ][ i ], 80, stdin ); // Never use gets(). Use fgets()
    
   }

   // previously, an empty for was present in your program i guess this is what you were trying
   for ( i = 0; i < 2; i++ ) {  
	  for ( k = 0; text[ i ][ k ] != '\0'; k++ ) {
		   text[ i ][ k ] = tolower (text[ i ][ k ] );
	  }
   }

    
   printf( "\nEnter a search character: "); 
   scanf( "%c", &search );

  // The loop was running to <= 2. Make it 0 to < 2 (2 lines)
  // also, the while was outside the for.
   for ( i = 0; i < 2; i++ ) { 
      searchPtr = &text[i][0];
      while ( searchPtr = strchr( searchPtr, search ) ) {
         ++count; 
         searchPtr++;
      }
   }	  	  
   
   printf( "The total occurrences of '%c' in the text is %d\n",
          search, count );
   
   return 0;  
}

This works fine now.

Edited 6 Years Ago by myk45: n/a

This article has been dead for over six months. Start a new discussion instead.