string header

I'm able to use all the string functionality in my program even though I have not declared #include <string> in my program. Can anyone tell me why?

#include <iostream>
using namespace std;

int main()
{
string str ="just a test";
cout << str << endl;
return 0;
}

I'm using gnu gcc on Ubuntu linux code::blocks ide.

Here is another example that works without #include <string>.

#include <iostream>
using namespace std;

int main(int argc, char **argv)
{
const string hexdigits = "0123456789ABCDEF";
cout << "Enter a series of numbers between 0 and 15"
<< "separated by spaces. Hit ENTER when finished: "
<< endl;
string result;
string::size_type n;
while(cin >> n)
if (n < hexdigits.size())
result += hexdigits[n];
cout << "Your hex number is: " << result << endl;
return 0;
}


Last edited on
not without more info.
I can guess: you are using visual studio, which is known to quietly bend the rules of the language at times.

> 'm able to use all the string functionality in my program even though I have not declared
> #include <string> in my program.

One standard library header may include all or parts of other standard library headers. There is no bending of the rules; it is expressly permitted by the standard.

For example, if we include the header <fstream>, we get (at least) the declarations of the constructors of file streams which has a parameter of type const std::string&; for that header to be compileable, at least the declaration of std::string would have to be available.

You may not be able to use all the string functionality if you do not #include <string>

For example, consider this program:
1
2
3
4
5
6
7
#include <iostream>

int main()
{
    const std::string str = "hello world!\n" ;
    std::cout << str ;
}

It compiles cleanly with the GNU and LLVM libraries on Linux (note that neither library is 'quietly bending' the rules),
http://coliru.stacked-crooked.com/a/5e17d16542816ce2

but it generates an error with the Microsoft library on Windows:
(operator<< for std::string has not been pulled in by #include <iostream>)
http://rextester.com/QWET28975

The sane thing to do is: if std::string is to be used, #include <string>
thanks.
Last edited on
JLBorges wrote:
if we include the header <fstream>, we get (at least) the declarations of the constructors of file streams which has a parameter of type const std::string&; for that header to be compileable, at least the declaration of std::string would have to be available.

There is a stronger (and more obscure) dependency: fstream::getloc() returns a std::locale by value, and locale::name() returns a std::string by value. This pulls in string's class definition. string's operator<< isn't part of that definition, of course
Last edited on
Topic archived. No new replies allowed.