2

I would like to use the string class. Should I also involve using namespace std;?

I thought #include <string> would be enough but in CLion when only one of these two (namespace or include) is absent, there are some errors.

What makes things more complicated, is that there is <string> or <strings.h>. What's the difference?

Joris Timmermans
  • 10,814
  • 2
  • 49
  • 75
Now.Zero
  • 1,147
  • 1
  • 12
  • 23

2 Answers2

6

<string> is C++ and provides the std::string class.

<string.h> is C (the C++ equivalent is <cstring>) and only provides functions to work on char*.

Don't use using namespace std; (see the C++ Core Guidelines).

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • Functions from `cstring`/`string.h` comprise e. g. memset, strchr, strlen, ... (printf family, incontrast, comes from `cstdio`/`stdio.h`). – Aconcagua Apr 10 '19 at 09:51
  • I don't understand what " is C++ and provides the std::string class." means. Is it that something like interface of string exists in std , but not implemented yet? And if I include then, I kinda imported the implemented-real string>? – Now.Zero Apr 10 '19 at 10:04
  • Not sure if the guidelines reference is good – there are good points in, but referencing another non-standard library excessively (GSL) is at least questionable in my eyes... – Aconcagua Apr 10 '19 at 10:05
  • @Rhee `#include ` is what you need; `` was short for the header named 'string' which defines an equally named class in namespace `std`. – Aconcagua Apr 10 '19 at 10:06
  • @Aconcagua The GSL is an implementation of Core Guidelines verification. The link itself is the official one, supported by members of the C++ committee. – Matthieu Brucher Apr 10 '19 at 10:36
  • Then question arises: Why doesn't it enter the standard directly (in namespace `std`)??? – Aconcagua Apr 10 '19 at 11:42
  • This is a quite recent effort of adding guidelines, so it takes time. You can actually see some of the content of the GSL that have made their way in the standard. – Matthieu Brucher Apr 10 '19 at 11:58
3

In C++ the using statement is not related to including the functionality of that namespace (or type). Instead, it allows you to use the namespace in the statement without a namespace prefix in the rest of the current scope (or compilation unit if you have the statement in global scope) after the using statement.

So you could either write

#include <string>

std::string my_string;

or

#include <string>
using namespace std;

string my_string;

As others have mentioned - the first version is more recommended than the second, because there's usually a reason that things are in their own namespace (such as the std namespace here). If you have a blanket using statement you may get unexpected name clashes or other issues. This is especially true if you do it in a header file, which you should never do unless you know exactly what the results will be and where.

Joris Timmermans
  • 10,814
  • 2
  • 49
  • 75