Hi,

I've written a code to count vowels and consonants. But it hangs and doesn't do anything when a function call is made or even before that at get statement. When I try to get a string from user to pass to the function to count vowels or consonants.

Here is the code

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include "iostream"
using namespace std;


int countVowels(char str1[])
{
	int countV = 0;
	int whitespace = 0;
	int i = 0;

	while(str1[i]!='\0')
	{ 
		if(str1[i]=='A' || str1[i]=='a')
			countV++;

		if(str1[i]=='E' || str1[i]=='e')
			countV++;

		if(str1[i]=='I' || str1[i]=='i')
			countV++;

		if(str1[i]=='o' || str1[i]=='O')
			countV++;

		if(str1[i]==' ')
			whitespace++;

		else
			//countc++; // do nothing
		i++;
	}

	return countV;
}


int main(void)
{
		
	char str[50];
	
	int countv,countc,whitespace;

	countv=0;countc=0,whitespace=0;

	char option = 'z';

	while(option != 'e')
	{
		printf("\n\n ***Vowels & Consonants*** \n\n\n a - Count the number of vowels in the string e - Exit the program.");
		
                std::cout<<"\n\n Your choice = ";
		std::cin>>option;

		int i = 0;

		if(option == 'a')
		{
				cout<<"\n\nEnter a string : ";
				gets(str);
				countv = countVowels(str);
				cout<<"\nThe total nos of vowels are " << countv;
		
		}

		
		else if(option == 'e')
		{
				exit('0');
		}
		
		else
		{
				printf("\nInvalide option. Please enter again\n");
		}

			
		

	}	
	getch();

	return 0;
}

Any help would be appreciated. thanks

At a glance, the following raises a red flag:

else
    //countc++; // do nothing
i++;

Since you've commented out the body of the else statement, the i++; statement becomes the body. So you only increment i when all of the other cases fail. That pretty much guarantees an infinite loop.

Yes, but the problem even starts before that. It starts somewhere at gets(str);

Program instead of waiting to take an input form the user it makes the function call

At a glance, the following raises a red flag:

else
    //countc++; // do nothing
i++;

Since you've commented out the body of the else statement, the i++; statement becomes the body. So you only increment i when all of the other cases fail. That pretty much guarantees an infinite loop.

cin>>option leaves a newline character in the stream. gets terminates successfully on that character immediately without blocking for input. The simplest solution is to add an ignore just after cin:

std::cin>> option;
std::cin.ignore();

Thanks, that solved the issue

cin>>option leaves a newline character in the stream. gets terminates successfully on that character immediately without blocking for input. The simplest solution is to add an ignore just after cin:

std::cin>> option;
std::cin.ignore();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.