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.

advertisement
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
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.

advertisement

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest 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
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.