C++ Program to Toggle Cases in a String

This is a C++ Program to Toggle Cases in a String.

Problem Description

The program takes a string and changes the cases of the string characters.

Problem Solution

1. The program takes a string.
2. Using ctype functions, uppercase characters are converted to lowercase and vice versa.
3. If entered string is not alphabetical, program is exited.
4. The converted string is printed.
5. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Toggle Cases in a String. The program output is shown below.

  1. #include<iostream>
  2. #include<string.h>
  3. #include<ctype.h>
  4. using namespace std;
  5. int main ()
  6. {
  7.     char str[50];
  8.     cout << "Enter a string : ";
  9.     gets(str); 
  10.     for (int i = 0; str[i] != '\0'; i++)
  11.     {
  12.         if (isalpha(str[i]))
  13.         {
  14.             if (islower(str[i]))
  15.                 str[i] = toupper(str[i]);
  16.             else
  17.                 str[i] = tolower(str[i]);
  18.         }
  19.         else
  20. 	{
  21.             cout << "Entered string is not alphabetical.";
  22.             exit(0);
  23.         }
  24.     }
  25.     cout << "Resultant string : " << str;
  26. }
Program Explanation

1. The user is asked to enter a string. It is stored in the character variable ‘str’.
2. Using a for loop, each character in the string is checked.
3. If it is an alphabet, it is further checked if it’s uppercase or lowercase.
4. If the character is uppercase, it is converted to lowercase, else vice versa.
5. If character is not an alphabet, the program is exited.
6. The converted string is then printed.

advertisement
Runtime Test Cases
Case 1 :
Enter a string : sPANISH
Resultant string : Spanish
 
Case 2 :
Enter a string : halo25
Entered string is not alphabetical.
 
Case 3 :
Enter a string : EUPHORIA
Resultant string : euphoria

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

🔥 Enroll Now for Free Python Certification - December 2025

advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 20s–40s and exploring new directions in your career, I also offer mentoring. Learn more here.