Why is using std::string still needed after #include <string>? [duplicate] - c++

This question already has answers here:
C++ namespace and include
(11 answers)
Closed 5 years ago.
In order to use strings I need to include the string header, so that its implementation becomes available. But if that is so, why do I still need to add the line using std::string?
Why doesn't it already know about the string data type?
#include <string>
using std::string;
int main() {
string s1;
}

Because string is defined within namespace called std.
you can write std::string everywhere where <string> is included but you can add using std::string and don't use namespace in the scope (so std::string might be reffered to as string). You can place it for example inside the function and then it applies only to that function:
#include <string>
void foo() {
using std::string;
string a; //OK
}
void bar() {
std::string b; //OK
string c; //ERROR: identifier "string" is undefined
}

using std::string; doesn't mean you can now use this type, but you can use this type without having to specify the namespace std:: before the name of the type.
The following code is correct:
#include <string>
int main()
{
std::string s1;
return 0;
}

Because the declaration of class string is in the namespace std. Thus you either need to always access it via std::string (then you don't need to have using) or do it as you did.

Namespace is an additional feature of C++, which is defining the scope of a variable, function or object and avoiding the name collision. Here, the string object is defined in the std namespace.
std is the standard namespace. cout, cin, string and a lot of other things are defined in it.
The header <string> declares the various entities related to the strings library, whereas namespaces are used to group related functionality and allow use of the same names in different namespaces.

Related

c++ class implementation with string function

I need to implement a class for one of my assignment and one of the function in the class that has string as datatype doesn't work
my definition code is :
#include <string>
class expression {
public:
expression();
void promptUser();
int getNum1();
int getNum2();
int calculate();
st::string str;
string numToString(int num);
string opToString();
private:
int num1;
int num2;
char op;
};
And in my implementation file
when I try to definite numTostring
string expression::numToString(int num) {
string digit;
...
It says that the declaration is incompatible with the header file(my class definition)
I have no idea why because both the function heading are the same.
the header file of expression.cpp( the implementation file) are :
#include "expression1.h"
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
Your class uses the unqualified name string, but there is no string data type defined in any enclosing scopes. There's a std::string data type defined in namespace std. That's looks to be the type that you need:
std::string str;
std::string numToString(int num);
std::string opToString();
You can keep from having to type out std:: everywhere by specifying a using statement:
using std::string;
But you might not want to do that inside a header file, so stick with fully qualifying the type.
If you want to use , you need to refer to it with std::
For example, your expression class declares:
st::string str;
string numToString(int num);
string opToString();
Which should be:
std::string str; // you typed st:: instead of std::
std::string numToString(int num); // lack of std::
std::string opToString(); // lack of std::
If you dont use 2 files (cpp + h) to define and declare your class then you can add line
using namespace std;
just after your includes. This way you wont have to type std:: each time you try to refer to string and similar types. However, using this is often called a bad "beginner" practice.
If you do use cpp+h then just add std:: before every string type and add using namespace std; to your cpp file.
If you want to know more then read:
1. http://www.cplusplus.com/doc/tutorial/namespaces/
2. Why is "using namespace std" considered bad practice?
3. How do you properly use namespaces in C++?
You also need to move
#include "stdafx.h"
up so it is the first header included. The compiler ignores everything that comes before that magic line.

Is it ok to wrap code in anonymous namespaces for using directives? [duplicate]

This question already has answers here:
Is using namespace in an anonymous namespace safe?
(2 answers)
Closed 3 months ago.
I want using namespace std; to apply to classes as well as functions without polluting the global namespace, but I'm wondering if it's an ok approach.
namespace
{
using namespace std;
class S
{
public:
S()
{
cout << "ok";
}
friend ostream operator<<(ostream& os, const S& s);
};
}
Any caveats to this?
It will work but keep in mind the following points:
You should limit its use in a source file, not in a header file (in general you should refrain from using unnamed namespaces in headers since they can easily mess around with your symbol definitions, especially if there are inline functions that use something from the anonymous namespace).
It's a bad practice and adding an additional naming hierarchy layer (i.e. the anonymous namespace) just for laziness is as bad as it sounds.
If it's in header file then it's not preferable as this file could be included in multiple source file. If in some source file then its acceptable
Whilst this looked like a great solution, in my experiments it doesn't do as I expected it would. It doesn't limit the scope of the using directive.
Consider this:
#include <string>
namespace {
string s1; // compile error
}
namespace {
string s2; // compile error
}
string s3; // compile error
int main()
{
}
None of those strings compile because they are not properly qualified. This is what we expect.
Then consider this:
#include <string>
namespace {
using namespace std;
string s1; // compiles fine (as expected)
}
namespace {
string t2; // compiles fine (I didn't expect that)
}
string v3; // compiles fine (I didn't expect that either)
int main()
{
}
So placing a using directive within an unnamed namespace appears to be exactly the same as placing it in the global namespace.
EDIT: Actually, placing a symbol in an unnamed namespace makes it local to the translation unit. So this is why it can't work for the intended purpose.
Therefore it has to be a no-no for headers.
An unnamed namespace doesn't contain the effects of a using-directive:
namespace A {int i;}
namespace {
using namespace A;
}
int j=i,k=::i; // OK
Both qualified and unqualified lookup follow the implicit using-directive for the unnamed namespace and then follow the explicit one within it. Wrapping the unnamed namespace inside another namespace limits the unqualified case to other code within that outer namespace, of course:
namespace A {int i;}
namespace B {
namespace {
using namespace A;
}
int j=i; // OK, as above
}
int j=i, // error: i not found
k=B::i; // OK
However, in either case you might as well write the using-directive outside the unnamed namespace (or not write it at all if it would be problematic, perhaps because it would appear in a header file).
Don't take the decision to use an anonymous namespace just so you can limit the scope of a using directive.
That being said, if an anonymous (or any other) namespace is already there and you want the advantages of the using inside it, it's fine as long as your coding standards okay it.

C++ std::string and string

I don't suppose anyone tell me whats the difference between using the std::string and just the string data type in C++??
In what situation should the std::string should be used over the standard string??
Thanks.
They're both the same type. std::string specifies the namespace, while string only makes sense if a using namespace std; or using std::string statement is used. So it doesn't make any difference what you use (as long as you're consistent).
If you're talking about the string literals (such as "hello"), then they're of type const char [], that implicitly decays in a const char *. std::string has a non-explicit constructor that takes a const char *, this allowing implicit conversion from const char * to std::string. The opposite operation can be done with the std::string::c_str() method.
If you're looking for a reason to use std::string instead of const char *, then I guess my answer would be "as much as you can".
These are likely the same thing within your program. The "standard" string resides within the "std" namespace. If you are "using std::string;" or "using namespace std;" within the module, then they are equivalent. If you aren't specifying a "using" statement, then you are required to provide the namespace of the object. It's preferable to not provide "using" statements within the header file and therefore you will typically see namespace resolution/specifiers on objects. (i.e. std::vector, mynamespace::myclass, etc.). The use of "using" is more common in implementation files where they won't affect other files as they would if specified in a header file.
It's possible to use a string object from another provider. In this case the provider would/should have their string object implementation in their own namespace and you would need to declare which string object you were using.
So:
File: stdString.cpp
-------------
#include <string>
#include "providerx/string.h"
using namespace std;
void foo()
{
string x; // Using string object provided by the C++ standard library
std::string y; // Again, using C++ standard lib string
providerx::string // Using string object defined within the providerx namespace
}
File: providerString.cpp
-------------------
#include "providerx/string.h"
using providerX::string;
void foo()
{
string x; // Using providerx string object
}
Most likely, you have using namespace std somewhere in your code. This is allowing you to access members of the std namespace without resolving the scope. Therefore...
std::string == string

Why can't I declare a string in my program: "string is undeclared identifier"

I can't declare a string in my program:
string MessageBoxText = CharNameTextBox->Text;
it just doesn't work. It says string is undeclared identifier. What am I missing in the namespace or include or something like that?
Make sure you've included this header:
#include <string>
And then use std::string instead of string. It is because string is defined in std namespace.
And don't write this at namespace scope:
using namespace std; //bad practice if you write this at namespace scope
However, writing it at function scope is not that bad. But the best is one which I suggested before:
Use std::string as:
std::string MessageBoxText = CharNameTextBox->Text;
To use the standard string class in C++ you need to #include <string>. Once you've added the #include directive string will be defined in the std namespace and you can refer to it as std::string.
E.g.
#include <string>
#include <iostream>
int main()
{
std::string hw( "Hello, world!\n" );
std::cout << hw;
return 0;
}
Are you by any way compiling using C++/CLI, the Microsoft extension for .NET, and not standard ISO C++?
In that case you should do the following:
System::String^ MessageBoxText = CharNameTextBox->Text;
Also see the following articles:
How to: Convert Between Various String Types
How to: Convert System::String to Standard String
How to: Convert Standard String to System::String

C++ string in classes

I know this is quite a ridiculous question but this is quite confusing and irritating, as something that should work simply is not. I'm using Code Blocks with the GCC compiler and I am trying to simply create a string variable in my class
#ifndef ALIEN_LANGUAGE
#define ALIEN_LANGUAGE
#include <string>
class Language
{
public:
private:
string str;
};
#endif
Strange enough, my compiler halts me with an error saying this:
C:\Documents and Settings\...|11|error: `string' does not name a type|
||=== Build finished: 1 errors, 0 warnings ===|
For some reason, it is unable to find the class "string" which for some reason, my main.cpp is able to detect "#include " while my language class is not able for some reason.
This is the main I wrote quickly just to see it main itself is able to see the string file:
//main.cpp
#include <iostream>
#include <string>
#include "alien_language.h"
using namespace std;
int main()
{
string str;
return 0;
}
Does anyone know what's going on?
using namespace std;
That's what's going on.
You don't have std:: prefixing the string in your class. Everything in the standard library is in the namespace std.
It is generally regarded as bad practice to use using namespace std;, by the way. For more information on why and what to do instead, check out this question: Using std Namespace.
The string class is defined in the std namespace. You should chenge the class to this:
class Language
{
public:
private:
std::string str;
};
It is also possible, but not recommended to add this to the top of the header file:
using namespace std;
string is in namespace std, and you need to qualify it fully inside your header file:
#include <string>
class Language
{
public:
private:
std::string str;
};
Do not use using namespace std; or similar in header files.
You should refer to it as std::string;
It looks to me like you're missing the all-important (with a hint of sarcasm) using namespace std; line. Either add that in before your class, or explicitely use std::string str. I'd recommend against adding the using namespace std; line in a header file, as it would pollute the mainspace for any file that includes it.
The string class in standard C++ is in std namespace. Write something like
using std::string; in your header or fully qualify it as std::string in your header.
Beware that using namespace std; in header is a bad practice (read here).