954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

C++ Question Mark counter-- Any Improvements in Code?

Hey all,
I have decided that in order to learn i will need to write code. So i am working on all the questions on my book. And as I am teaching myself i end up with no-one to scrutinize my code.

#include <iostream>

/************Declarations of Functions*********/
	void func1();
	void func2();
//=============================================Tue 28 Apr 2009 18:37:48 IST//
/* Global Test Variables */

	int const max_length=18;
	int quest_count=0 ;
	char input_line[max_length]="???sky???";


int main()
{	

	func1();// Character string with While loop
	std::cout<<"No Of Question Marks = " << quest_count<< "\n";
	quest_count=0;
	func2();//Pointer Based Passing.
	std::cout<<"No Of Question Marks(Pointer Based) = " << quest_count<< "\n";
}

void func1()
{
	int i=0;
	while(i<max_length)
		{
			if(input_line[i]=='?')
			quest_count++;
		i++;
		}
}

void func2()
{

	char *ptr=input_line;
	while(*ptr!=0)
	{
		if(*ptr=='?')
			{
			quest_count++;
			}
		*ptr++;
	}

}


The above program counts the number of "?" marks in a string passed to it.

I would like to recieve comments on the code :) and any improvements that can be made.

Sky Diploma
Practically a Posting Shark
865 posts since Mar 2008
Reputation Points: 673
Solved Threads: 131
 

I think it would be more useful if one could pass the string into a method and have it return the number of question-marks found (as an unsigned int, or in extraordinary cases an unsigned long int).

Alex Edwards
Posting Shark
972 posts since Jun 2008
Reputation Points: 392
Solved Threads: 109
 

Thanks for the reply.

Sky Diploma
Practically a Posting Shark
865 posts since Mar 2008
Reputation Points: 673
Solved Threads: 131
 

I would define a constant char for the '?' comparer. If you want to change the compare criteria, you only have to change it once.

lqdo
Newbie Poster
24 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You