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 - June 2026

👉 For weekly programming practice and certification updates, join Sanfoundry’s official WhatsApp & Telegram channels
advertisement
Manish Bhojasia – Founder & CTO at Sanfoundry

I’m Manish, Founder & CTO at Sanfoundry, with 25+ years of experience across Linux systems, SAN technologies, advanced C programming, and building large-scale, performance-driven learning and certification platforms focused on clear skill validation.

LinkedIn  ·  YouTube MasterClass  ·  Telegram Classes  ·  Career Guidance & Conversations