#include <iostream>
#include <string>
#include <cctype>
using std::string;
using std::cin;
using std::cout; using std::endl;
int main()
{
string s("Hello World!!!");
decltype(s.size()) punct_cnt = 0;
for (auto c : s)
if (ispunct(c))
++punct_cnt;
cout << punct_cnt
<< " punctuation characters in " << s << endl;
}
It seems that I can use ispunct()
without std::
or declaring using std::ispunct;
but I can't do that with std::cout
or std::cin
. Why is this happening?
It means ispunct
is part of the global namespace, rather than the std
namespace. This is probably because ispunct
is one of the functions brought over from C (hence it is in cctype
).
On the other hand, cout
and cin
are part of the std
namespace, not the global namespace.
As to why things from C are in the global namespace instead of in the std
namespace, I believe it has to do with allowing C code to compile by a C++ compiler with minimal changes, since C++ aims to be compatible with C.
According to the comments, ispunct
is allowed, but not required, to be in the global namespace (but is required to be in the std
namespace), in <cctype>
. However, if you had included <ctype.h>
instead, ispunct
would be required to be in the global namespace.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With