Why do I get an error when using string in a .h file?
Error: 'string' does not name a type
When I use string with the main function it works fine. But, when I try to use the string class in a .h file I get the error, even though I included the string library. Also, the code works fine if I use a char* type instead of string.
#include <iostream>
#include "Signature.h"
usingnamespace std;
int main()
{
// signature block
cout << SIGNATURE << endl;
// request user's name and store in a variable
string name;
cout << "What is your name? ";
getline( cin, name );
// print "Hello" and the user's name
cout << "Hello, " << name << "!" << endl;
return 0;
}
@Austin J
It is generally bad practice to put usingnamespace std; in a header file. Well, it's bad practice to use it at all, but putting it in a header file forces all of those unwanted consequences upon any file which includes that header.
OK. Thanks for the help, it worked. Couple questions: Is it necessary to include the string library (#include <string>)? The code seems to work fine without it. Is string part of the the std namespace?
Yes, you should put the #include <string> in the header file. Without it, you are dependent upon that being indirectly included either by some other standard header, or in the file where the header is itself included.
Is string part of the the std namespace? Yes, that's why putting std:: in front of it works.
@Chervil
Yes I agree with you sorry I was vague,I disagree with usingnamespace for any namespace in general. I suppose I should have mentioned it's more appropriate to use std:: I always go with std::vector<T>someVector over usingnamespace std; /* later on */ vector<T>someVector
A good example navig8tr of why you should just go with typing the namespace each time is the SFML vector and STL vector. While you probably don't know what either of those are, you'll still understand my point.
std::vector or STL vector is a container, and for whatever reason was named a vector.
SFML vector can hold two values in one, commonly x,y coordinates.
I wouldn't be surprised if there's an API out there that has a "real" vector. A representation of an objects/forces direction and magnitude.
While the creator of SFML made sure not to name SFML vectors exactly as vector it's still good to keep them easy to differentiate on sight. So you use std:: before STL vector and sf:: before SFML vector.
I personally haven't used Boost but from what I can tell it's pretty important to keep your namespaces obvious when using it.
If you're going to use a variable for your signature, you should probably use a const char* in this case.
If you use a std::string you might well end up allocating memory on the heap pointlessly (I don't know if compilers are smart enough to, or allowed to, strip out the std::string construction.)