C++ Program to Demonstrate the use of String Class

This C++ Program which demonstrates the use of string class. The program uses a special header for using string class. A ‘string’ object is created, the name of the user is taken as input to save it into the string object, the length of string object is printed and also the string object is printed by going through the object by use of iterators.

Here is source code of the C++ program which demonstrates the use of string class. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to Demonstrate use of String Class
  3.  */
  4.  
  5. #include<iostream>
  6. #include<string>
  7. using namespace std;
  8.  
  9. int main()
  10. {
  11.     std::string s;
  12.     cout << "Enter your first name : ";
  13.     cin >> s;
  14.     cout << "The length of your name is " << s.length() << endl;
  15.     cout << "Nice to meet you ";
  16.  
  17.     /* Printing using const_iterator */
  18.     for (std::string::const_iterator i = s.begin(); i != s.end(); i++)
  19.         cout << *i;
  20.     cout << "!" << endl;
  21. }

$ g++ main.cpp
$ ./a.out
Enter your first name : George
The length of your name is 6
Nice to meet you George!

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

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

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 & discussions at Telegram SanfoundryClasses.