What is the difference between "using std::string" and "#include <string>"

I am newly learning C++, I do not really understand the difference between putting using std::string vs #include <string> at the top of my main file.

I seem to be able to define strings without having #include <string> here:

#include <iostream>
using std::cout; using std::cin;
using std::endl;
using std::string;

int main()
    string s = "hi";
    cout << s;
    return 0;

This seems to run without issue, so why would I have #include <string>?

>Solution :

You need to include the <string> header to use std::string.

Adding using std::string; allows you to use it without the std:: namespace qualifier.

If you include a header that includes <string> you may not have to do so explicitly. However, it is bad practice to count on this, and well-written headers include guards against multiple inclusion, so assuming you’re using well-written header files, there is no harm in including a header that was included via a previous include.

Leave a Reply