Course Content
C++ Introduction
C++ Introduction
Introduction to String
You can store text in variables using the string
type. To do this, you'll need to include the string
library, utilize the std
namespace scope resolution, and declare a variable of the string
type. This allows you to handle sequences of characters seamlessly in your programs.
main
#include <iostream> #include <string> int main() { // Declaring string variable std::string text = "codefinity"; // Displaying string variable std::cout << text << std::endl; }
Strings variables can also contain numbers (as text). However, it's important to note that while you can store numbers in this format, you cannot directly perform mathematical operations on these numbers while they're stored as strings.
main
#include <iostream> #include <string> int main() { std::string text = "1024"; // Displaying string variable std::cout << text << std::endl;; }
If you try to add two string variables, you get a concatenation (it works without spaces). The same thing will happen with numbers – they will not be added algebraically.
main
#include <iostream> #include <string> int main() { std::string first_part = "Hello "; //space is also a symbol std::string second_part = "World"; //displaying the sum of string variables std::cout << first_part + second_part << std::endl; }
Thanks for your feedback!