I'm trying to learn about string
s, but different sources tell my to include different headers.
Some say to use <string.h>
, but others mention "apstring.h"
. I was able to do some basic stuff with apstring
, but I've been told the other one is more powerful. When I include <string.h>
and try to declare some string variables, however, I get errors. What is the proper usage?
You make the declarations in a header file, then use the #include directive in every . cpp file or other header file that requires that declaration. The #include directive inserts a copy of the header file directly into the .
#include <string. h> Inclusion of <string> In C++ is recommended when the program needs to use string.
h is the header file required for string functions.
Use #include <string> when you use a variable that has type std::string . The code "text here" , contrary to intuition, is not a std::string ; it is a string literal, and a C-style string, and a const char[10] convertible to const char* . Welcome to C++ with its legacy oddities.
You want to include <string>
and use std::string
:
#include <string> #include <iostream> int main() { std::string s = "a string"; std::cout << s << std::endl; }
But what you really need to do is get an introductory level book. You aren't going to learn properly any other way, certainly not scrapping for information online.
Sources telling you to use apstring.h are materials for the Advanced Placement course in computer science. It describes a string class that you'll use through the course, and some of the exam questions may refer to it and expect you to be moderately familiar with it. Unless you're enrolled in that class or studying to take that exam, ignore those sources.
Sources telling you to use string.h are either not really talking about C++, or are severely outdated. You should probably ignore them, too. That header is for the C functions for manipulating null-terminated arrays of characters, also known as C-style strings.
In C++, you should use the string header. Write #include <string>
at the top of your file. When you declare a variable, the type is string
, and it's in the std
namespace, so its full name is std::string
. You can avoid having to write the namespace portion of that name all the time by following the example of lots of introductory texts and saying using namespace std
at the top of the C++ source files (but generally not at the top of any header files you might write).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With