16

I've been looking for an answer on websites but couldn't find any answer that helped me.

I have a code that uses strings when i tried (like suggested) to add these lines:

using namespace std;
using std::string;
#include <string>

I tried to use each of them separately and I tried all of them together. The best situation was when all of the string errors disappeared but I had another weird error on the line "using std::string" and the error was: std::string has not been declared. Any ideas? Thanks guys.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
wannabe programmer
  • 653
  • 1
  • 9
  • 23

2 Answers2

16

Put #include <string> first.

Avoid using statements in headers as you potentially bring in all sorts of stuff into many compilation units. using std::string is perhaps acceptable in a header but using namespace std certainly isn't as it will cause so much namespace pollution in all compilation units. The std namespace is continuously expanding (look at all the new stuff in C++), so you don't want to have to fix lots of errors when upgrading your compiler.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • I don't think `using std::string` is acceptable in a header, *unless* it is in a limited scope. – juanchopanza Jun 11 '13 at 09:03
  • @RoeeGavirel I know. But this answer explicitly speaks about headers. – juanchopanza Jun 11 '13 at 09:05
  • @juanchopanza; I agree with you (it's one of the standards I enforce). – Bathsheba Jun 11 '13 at 09:08
  • 1
    Some possibly helpful terminology: `using namespace std;` is a using directive. `using std::string;` is a using declaration. – Luc Danton Jun 11 '13 at 09:10
  • @juanchopanza: I use it along with vector and plenty other using declarations in the common header that is forced include for all projects. With the best results. Using std:: on exotic stuff is tolerable, but otherwise is is just utter noise. Do you allow reusing name 'string' for other purposes? – Balog Pal Jun 11 '13 at 09:24
  • @BalogPal I wouldn't allow to re-use `string` or `vector` or many other names, but people do it anyway. The number of times I've seen things called `list`, `map` or `set`... – juanchopanza Jun 11 '13 at 09:43
  • so don't let people do it anyway... how hard it is to spot on a review really? – Balog Pal Jun 11 '13 at 09:46
1

The include should come before the using

#include <string>
using namespace std;
//using std::string; <-- Needless
Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94