CPP program to check valid Identifier

C++ program to check the validity of any input string whether the inputted string is a valid identifier or invalid identifier.  While developing this program we followed the basic rules of a valid identifiers in C/C++.

  1. All the valid identifiers should either start with alphabet or underscore (_).
  2. It should not contain any special character or punctuation marks.

The source code of this program checks these two basic rules.

/*	Program to find out whether an inputed word is a valid identifier or not. 
	made by		: 	rakesh kumar
*/
#include
#include
#include
#include
using namespace std;
int main()
{
	char str[100];
	int i;
	int valid = 1;   // for checking validity
	//input phase
	cout<<"\n Enter any identifier :";
	cin.getline(str,100);
	//processing phase
	cout<<"\n Entered Identifier :"<<str;
	
	if(isalpha(str[0])||str[0]=='_')
	   valid = 1;
	else
		valid = 0;
		
	if(valid==1)
	  {
	  	for(i=1;i<strlen(str);i++)
	  	   {
	  	   	if(!(isalpha(str[i]) || isdigit(str[i])|| str[i]=='_'))
				{valid = 0; break;}
	  	   }
	  }
	//output phase
	if(valid == 0 )
		cout<<"\n Invalid identifier";
	else
		cout<<"\n Valid Identifier";
	return 0;
}

Above program was developed on Windows 10 Using Dev C++ IDE. The output of valid Identifier program is as follows.

C/C++ program to check validity of given identifier
Identifier validity checker program output
%d bloggers like this: