Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading