How to detect special character in a string in C++

In this post, we are going to learn about how to detect special character in a string in C++. All characters except alphabets and digits are regarded as special characters in C++.  So we are going to use ASCII values to detect special character in a string. Let us try to understand what is ASCII value.

ASCII value

All characters which may be digits, alphabets or special character has an ASCII value associated with it.

ASCII value ranges:

  • Digits: 48-57
  • Capital alphabets: 65-90
  • Small alphabets: 97-122
  • All other characters are special characters.

Code in C++ to detect special character in a string

// Program to detect special character in a string. 
#include<bits/stdc++.h>
using namespace std; 
int main()
{
  // Input a string 
  string str;
  cout<<"Enter a string: ";
  getline(cin,str);
  int flag=0;
  
  // Checking if string contians special character
  for(int i=0;i<str.length();i++)
  {
    if ((str[i]>=48 && str[i]<=57)||
        (str[i]>=65 && str[i]<=90)||
        (str[i]>=97 && str[i]<=122))
        {
        	continue;
        }
    else
    {
      cout<<"String contains special character.\n";
      flag=1;
      break;
    }
  }
  if(flag==0)
  {
    cout<<"There is no special character in the string.\n";
  }
  return 0;
}

Input:

Enter a string: Code!speedy

Output:

String contains special character.

You may also learn,

Finding Minimum Cost Path in a 2-D Matrix in C++

How to Terminate a Loop in C++?

Do not forget to comment if you find anything wrong in the post or you want to share some information regarding the same.

One response to “How to detect special character in a string in C++”

  1. Rishon Jonathan R says:

    there is no error in the code,but some compilers generally don’t recognize the library.the iostream library is missig

Leave a Reply

Your email address will not be published. Required fields are marked *