Question

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 ?

Was it helpful?

Solution

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;
}

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top