2

I am using namespace std;

Then, what's wrong with coding this?

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

As far as I know, I should put the "using namespace" or prefix the std:: each time interchangeably, but not both at the same time. What are the disadvantages of mixing both?

Also, how can I replace the code above? Is this acceptable?

cin.ignore(numeric_limits<streamsize>::max(), '\n');
ks1322
  • 33,961
  • 14
  • 109
  • 164
  • 1
    It is up to you. Personally I think its preferable to explicit std:: before every function call to remember it is a standard library function, and to avoid possible conflicts if you define a function with the same name. But for small projects it really does not matter. – Noel Dec 03 '14 at 15:17

2 Answers2

1

I am using namespace std;

That's usually a bad idea, unless it's in a narrow scope to keep the pollution away from the rest of the program.

Then, what's wrong with coding this?

Nothing; it's just more verbose than it needs to be. The name is available both as a qualified std::cin in any scope, and an unqualified cin in any scope where the name has been dumped by using. But I'd suggest not dumping the contents of the standard library into any other scope, to avoid the danger of library names conflicting with names I want to use.

What are the disadvantages of mixing both?

You have both the name pollution that namespaces help avoid, and the less readable qualified names that using helps avoid; the disadvantages of both and the advantages of neither.

Also, how can I replace the code above?

As you say, cin.ignore(numeric_limits::max(), '\n'); will work if the contents of std have been dumped into an accessible scope. But I'd still recommend getting rid of the using.

Community
  • 1
  • 1
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

If you are already going to the effort of prefixing your functions with std:: then you really gain nothing by also having using namespace std; but you get the downsides that come with pulling everything from the standard library namespace in. Definitely don't do both. Also don't put using namespace std in your header files because the users of your code probably don't want that. Doing so is making a presumption that the users of your headers don't have any names that conflict with any of the standard library names, if this isn't the case then it's a pain for your users.

Generally speaking I usually always prefix with std:: just to make sure that there's no name conflicts. However if there is a situation where you are just trying to reduce on typing then you can explicitly pull in just the name you want. For example:

 using std::cout;
 cout << "foo";

In this case you can reduce some typing without polluting the namespace by bringing in everything.

shuttle87
  • 15,466
  • 11
  • 77
  • 106