How to Create String in C++: Syntax and Examples
In C++, you create a string using the
std::string class by including the <string> header and declaring a variable like std::string name = "Hello";. This lets you store and manipulate text easily.Syntax
To create a string in C++, you use the std::string class from the <string> header. You declare a string variable and assign text to it using double quotes.
- std::string: The string type from the C++ Standard Library.
- variable name: Your chosen name for the string.
- = "text";: Assigns the text to the string variable.
cpp
#include <string>
std::string variable_name = "text";Example
This example shows how to create a string, assign text, and print it to the console using std::cout.
cpp
#include <iostream> #include <string> int main() { std::string greeting = "Hello, world!"; std::cout << greeting << std::endl; return 0; }
Output
Hello, world!
Common Pitfalls
Common mistakes when creating strings in C++ include:
- Forgetting to include the
<string>header, which causes errors. - Using single quotes
' 'instead of double quotes" "for string literals. - Trying to assign a C-style string (char array) directly without using
std::string.
Always use std::string for easy and safe string handling.
cpp
#include <iostream> // Wrong: missing <string> header // std::string name = 'Hello'; // Wrong: single quotes for string #include <string> int main() { std::string name = "Hello"; // Correct std::cout << name << std::endl; return 0; }
Output
Hello
Quick Reference
Summary tips for creating strings in C++:
- Always #include <string> before using
std::string. - Use double quotes
"text"for string literals. - Declare strings as
std::string variable = "text";. - Use
std::coutto print strings.
Key Takeaways
Use
std::string from the <string> header to create strings in C++.Always enclose text in double quotes when assigning to a string variable.
Include
<string> to avoid compilation errors.Use
std::cout to display strings on the console.Avoid using single quotes for strings; they are for single characters.