1

I wrote a simple program like below:

#include <iostream>
#include <string>
int main()
{
   string a;
   std::cin >> a;
   std::cout << a << std::endl;
   return 0;
}

It failed to compiled and the compiler suggest me to use std::string instead of string. After using std::string, everything is fine.

My question is why my program needs to use std::string in order to be compiler successfully ?

7
  • 1
    using namespace std Commented Mar 28, 2014 at 2:54
  • 3
    because string is the class provided by standard and it has been defined under std namespace.Hence compiler gives the error. Commented Mar 28, 2014 at 2:54
  • put a using namespace std before the use of string will allow you to use the std::string class without the namespace prefix. Commented Mar 28, 2014 at 2:54
  • The program is in the global namespace. If you want to access something in a namespace you prefix it. Or you can put using namespace std; just after the includes - although you might not want to pull everything in std into your program. Commented Mar 28, 2014 at 2:55
  • 5
    using std::string; is a safer idea than using namespace std;. The latter gets you hundreds of things, some of which might have unexpected side effects. Commented Mar 28, 2014 at 2:56

2 Answers 2

1

The string class is in the namespace std. You can remove the scoping for std::.

You'd do best to include it inside the main function, so names don't colide if you use a library that uses the name string or cout, or such.

#include <iostream>
#include <string>

int main()
{
  using namespace std;
  string a;
  cin >> a;
  cout << a << endl;
  return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

0

string is in std namespace, it's only valid to use std::string rather than string (the same for std::cin, std::vector etc). However, in practice, some compilers may let a program using string etc without std:: prefix compile, which makes some programmers think it's OK to omit std::, but it's not in standard C++.

So it's best to use:

#include <iostream>
#include <string>
int main()
{
   std::string a;
   std::cin >> a;
   std::cout << a << std::endl;
   return 0;
}

Note that it's NOT a good idea to use using namespace std; (though it's legal), especially NOT put it in a header.

If you are tired of typing all the std::, declare all the names with namespace you use is one option:

#include <iostream>
#include <string>
using std::string;
using std::cin;
using std::cout;
using std::endl;
int main()
{
   string a;
   cin >> a;
   cout << a << endl;
   return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.