Course Content
C++ Introduction
C++ Introduction
Introduction to String
You can also store text in variables, in addition to symbols using char
. For this, you need to:
- Connect the
string
file; - Use std scope resolution;
- Declare a variable of type
string
.
main
#include <iostream> #include <string> int main() { //declaring string variable std::string myStringVariable = "codefinity"; //displaying our string variable std::cout << myStringVariable << std::endl; }
Strings variables can also contain numbers (as text):
main
#include <iostream> #include <string> int main() { std::string myStringVariable = "1024"; //displaying our string variable std::cout << myStringVariable << std::endl;; }
If you try to add two string variables, you get a concatenation (it works without spaces):
main
#include <iostream> #include <string> int main() { std::string var1 = "Hello "; //space is also a symbol std::string var2 = "World"; //displaying the sum of string variables std::cout << var1 + var2 << std::endl; }
The same thing will happen with numbers – they will not be added algebraically.
Thanks for your feedback!