How to Declare a String in C++
One useful class in the C++ standard library is the string class. The string class was designed as a safer and easier alternative to the so-called "C style" strings, or char arrays. C++ strings do not run the risk of accidental buffer overrun, can expand themselves as needed, and provide a set of functions to edit and search through themselves.
Instructions
-
Add the std Namespace
-
1
Add the std namespace with the "using" keyword. For example, type:
using namespace std;
-
2
Declare a string, optionally using a constructor to assign a starting value. For example, type:
using namespace std;
string example_string;
string constructor_string("This is the string's text.");
-
-
3
Assign values to strings as you would other variables. Strings can be added to each other and assigned using the normal +, = and += operators.
using namespace std;
string example_string;
string constructor_string("This is the string's text.");
example_string = "This is the string's assigned value.";
example_string += " This text was added to the string's original value."
-
1
References
- Photo Credit Stockbyte/Stockbyte/Getty Images