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.cpp
1234567891011#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.cpp
12345678910#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.cpp
1234567891011#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!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Awesome!
Completion rate improved to 4
Introduction to String
Swipe to show menu
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.cpp
1234567891011#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.cpp
12345678910#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.cpp
1234567891011#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!