#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.
Edit:
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.
C names (those you get from including a xxx.h header from C) are allowed to be in the global namespace in addition to the ::std namespace even if you are including the cxxx version of the header. This has been done because it can be a problem not to have those in the global namespace if you provide the C++ implementation, but not the C implementation (so the actual C headers are from a compiler you don't control).
In your case, ispunct comes from the header ctype.h. While you are including the cctype header, this in turn includes the ctype.h header which declares the symbol ispunct in the global namespace.
C++ headers derived from C (such as <cctype>) are required to put the names of things that they declare in the namespace std and they are permitted to also put them in the global namespace. Formally, this wasn't allowed until C++11, but the old rule that those headers were not allowed to put names into the global namespace could not be implemented reasonably and was commonly ignored.
Related
#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.
Edit:
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.
C names (those you get from including a xxx.h header from C) are allowed to be in the global namespace in addition to the ::std namespace even if you are including the cxxx version of the header. This has been done because it can be a problem not to have those in the global namespace if you provide the C++ implementation, but not the C implementation (so the actual C headers are from a compiler you don't control).
In your case, ispunct comes from the header ctype.h. While you are including the cctype header, this in turn includes the ctype.h header which declares the symbol ispunct in the global namespace.
C++ headers derived from C (such as <cctype>) are required to put the names of things that they declare in the namespace std and they are permitted to also put them in the global namespace. Formally, this wasn't allowed until C++11, but the old rule that those headers were not allowed to put names into the global namespace could not be implemented reasonably and was commonly ignored.
I am a beginner in C++. From what I understand, in order to use a name, we have to include the library that consist of that name. Thereafter, we can either prepend the name of the namespace or use the using keyword.
E.g.
Without using keyword:
std::cout << "Hello Word!" << std::endl;
With using keyword:
using namespace std;
cout << "Hello World!" << endl;
I saw a working code sample online that uses the isalpha name from the locale library in the std namespace. However, that sample does not use any of the methods mentioned above.
E.g.
#include <iostream>
#include <locale>
int main() {
std::cout << isalpha('a') << std::endl;
}
Could someone please explain to me why the code still works?
When you include a C++ header for a C library facility, that is, a header <cfoo> corresponding to a C header <foo.h>, then the names from the C library are declared in namespace std. However, additionally it is unspecified whether the names are also declared in the global namespace.
In your case it seems that they are. But you cannot rely on that, nor should you.
There are two correct variants, as follows:
// C++ header
#include <cctype>
int main()
{
return !std::isalpha('a');
}
// C header
#include <ctype.h>
int main()
{
return !isalpha('a');
}
A compiler is permitted to declare extra names beyond those specified by the Standard, but your code is not portable if it relies on such artefacts of the implementation.
Always include the correct headers for the functions you use, and you will avoid surprises.
I am currently using Teach Yourself C++ in 21 Days, Second Edition book to learn about C++ coding, along with Microsoft Visual C++ 2010 Express. At the end of Chapter 1, there is a small exercise about writing and compiling the following code:
#include <iostream>
int main ()
{
cout << "Hello World!\n";
return 0;
}
Quite simple, right? However to my surprise the code would not compile, due to this error:
error C2065: 'cout' : undeclared identifier
I began scouring the Web, and soon found some solutions here. Turns out I had to add
using namespace std; to my code!
However there was no mention of namespaces in the book, so I figured the book is outdated. (It uses #include <iostream.h> pre-processor directive!) After some more Web research I found a lot of information about namespaces, namespace std, along with some historical background on <iostream.h> and <iostream>, and all this flow of new information is quite confusing to me. (Not to mention all the unnecessary Google results about medical STDs...)
So here are some questions I've got so far:
If I am including the iostream library, why is a namespace needed to find cout? Is there another cout somewhere that could cause a name clash? If someone could provide a diagram for this, that'd be great.
And as a bonus, some historical background:
What exactly was iostream.h before it was changed to iostream?
Did namespace play a part in this change?
All of the standard library definitions are inside the namespace std. That is they are not defined at global scope, so in order to use them you need to qualify them in one of the following way:
std::cout
using namespace std
using std::cout
For instance lets take this:
// declarations
int global_variable;
namespace n {
int variable2;
}
global_variable can be access as it is:
int x;
x = global_variable;
But variable2 is not part of the global space, but part of the namespace n.
int x;
x = variable2; // error variable2 identifier not found.
So you have to use the fully qualified name:
int x;
x = n::variable2;
As a shortcut you can write:
using namespace n;
int x;
x = variable2; // variable2 is searched in current namespace
// and in all namespaces brought in with using namespace
// Found ONLY in namespace n -> OK
or
using n::variable2; // this makes any unqualified reference to `variable2`
// to be resolved to `n::variable2`
int x;
x = variable2;
As for the header files, iostream.h was used by many compilers before there was a standard. When the committee tried to standardize they decided to make the C++ headers extensionless in order not to break compatibility with existing code.
Because this line starts with #, it is called a "preprocessor directive". The preprocessor
reads your program before it is compiled and only executes those lines beginning with #. The preprocessor sets up your source code for the compiler.
The #include directive causes the preprocessor to include the contents of another file into the program. The iostream file contains code that allows a C++ program to display output to the screen and take input from the keyboard. The iostream files are included in the program at the point the #include directive appears. The iostream is called a header file and appears at the top or head of the program.
using namespace std;
C++ uses namespaces to organize names or program entities. It declares that the program will be assessing entities who are part of the namespace called "std." Every name created by the iostream file is part of that namespace.
1.If I am including the iostream library, why is a namespace needed to find cout? Is there another cout somewhere that could cause a name clash?
It is needed because the C++ standard requires that cout be inside the std namespace. There could be a clashing cout, but not in the standard library (e.g. your own code, or some third party library.)
1.What exactly was iostream.h before it was changed to iostream?
It could be anything, because it is not part of the standard, but it was the name of a pre-standardization header which formed the basis for iostream. Usually, it declared all names in the global namespace, so it is likely that the example you are looking at was written pre-standardization.
2.Did namespace play a part in this change?
This question is unclear. The keyword namespace may be used inside implementations, and it is used to declare and define data, functions, types etc. inside a namespace. So it did have some part in this change.
namespace foo
{
void bar(); // declares foo::bar
}
In C++, you can logically group identifiers into namespaces.
cout stream is inside namespace std. You can use it in 3 ways.
Write using namespace std at top and use cout as you did.
Write using std::cout at top and use cout as you did.
Use std::cout instead of cout
Thanks to #bolov ..to understand the point referring this standard, this is the declaration:
#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>
namespace std
{
extern istream cin;
extern ostream cout;
extern ostream cerr;
extern ostream clog;
extern wistream wcin;
extern wostream wcout;
extern wostream wcerr;
extern wostream wclog;
}
With new version of c++ namespace was included. iostream contains all the declarations for input and output. Namespace std is used to tell that we are using cout and cin which were part of std namespace. You can create your own variables named cout and cin in your own namespace.
I had the same question as you. I am just going to teach you in laymen terms.
Imagine that you need a pencil which is placed in a drawer which is present in your bedroom. So you need to enter in your room to access your pencil. Here room is iostream. After you entered your room, you need to open the drawer and access the pencil. Here drawer is namespace and pencil is cin/cout.
Reference:- https://en.wikiversity.org/wiki/C%2B%2B/Introduction
for using cout, I need to specify both:
#include<iostream>
and
using namespace std;
Where is cout defined? in iostream, correct? So, it is that iostream itself is there in namespace std?
What is the meaning of both the statements with respect to using cout?
I am confused why we need to include them both.
iostream is the name of the file where cout is defined.
On the other hand, std is a namespace, equivalent (in some sense) to java's package.
cout is an instance defined in the iostream file, inside the std namespace.
There could exist another cout instance, in another namespace. So to indicate that you want to use the cout instance from the std namespace, you should write
std::cout, indicating the scope.
std::cout<<"Hello world"<<std::endl;
To avoid the std:: everywhere, you can use the using clause.
cout<<"Hello world"<<endl;
They are two different things. One indicates scope, the other does the actual inclusion of cout.
In response to your comment
Imagine that in iostream two instances named cout exist, in different namespaces
namespace std{
ostream cout;
}
namespace other{
float cout;//instance of another type.
}
After including <iostream>, you'd still need to specify the namespace. The #include statement doesnt say "Hey, use the cout in std::". Thats what using is for, to specify the scope
If your C++ implementation uses C style header files (many do) then there is a file that contains something similar to:
#include ... // bunches of other things included
namespace std {
... // various things
extern istream cin;
extern ostream cout;
extern ostream cerr;
... // various other things
}
std is the namespace that the C++ standard says most of the standard things should reside in. This is to keep from overpopulating the global namespace, which could cause you difficulty in coming up with names for your own classes, variables, and functions which aren't already used as names for standard things.
By saying
using namespace std;
you are telling the compiler that you want it to search in the namespace std in addition to the global namespace when looking up names.
If the compiler sees the source line:
return foo();
somewhere after the using namespace std; line it will look for foo in various different namespaces (similar to scopes) until it finds a foo that meets the requirements of that line. It searches namespaces in a certain order. First it looks in the local scope (which is really an unnamed namespace), then the next most local scope until over and over until outside of a function, then at the enclosing object's named things (methods, in this case), and then at global names (functions, in this case unless you've been silly and overloaded () which I'm ignoring), and then at the std namespace if you've used the using namespace std; line. I may have the last two in the wrong order (std may be searched before global), but you should avoid writing code that depends on that.
cout is logically defined within iostream. By logically, I mean it may actually be in the file iostream or it may be in some file included from iostream. Either way, including iostream is the correct way to get the definition of cout.
All symbols in iostream are in the namespace std. To make use the the cout symbol, you must tell the compiler how to find it (i.e. what namespace). You have a couple of choices:
// explicit
std::cout << std::endl;
// import one symbol into your namespace (other symbols must still be explicit)
using std::cout;
cout << std::endl;
// import the entire namespace
using namespace std;
cout << endl;
// shorten the namespace (not that interesting for standard, but can be useful
// for long namespace names)
namespace s = std;
s::cout << s::endl;
The #include <iostream> references the header file that defines cout. If you're going to use cout, then you will always need the include.
You do not need to using namespace std;. That's simply allows you to use the shorthand cout and endl and the like, rather than std::cout and std::endl where the namespace is explicit. Personally I prefer not to use using namespace ... since it requires me to be explicit in my meaning, though it is admittedly more verbose.
This question may be a duplicate, but I can't find a good answer. Short and simple, what requires me to declare
using namespace std;
in C++ programs?
Since the C++ standard has been accepted, practically all of the standard library is inside the std namespace. So if you don't want to qualify all standard library calls with std::, you need to add the using directive.
However,
using namespace std;
is considered a bad practice because you are practically importing the whole standard namespace, thus opening up a lot of possibilities for name clashes. It is better to import only the stuff you are actually using in your code, like
using std::string;
Nothing does, it's a shorthand to avoid prefixing everything in that namespace with std::
Technically, you might be required to use using (for whole namespaces or individual names) to be able to use Argument Dependent Lookup.
Consider the two following functions that use swap().
#include <iostream>
#include <algorithm>
namespace zzz
{
struct X {};
void swap(zzz::X&, zzz::X&)
{
std::cout << "Swapping X\n";
}
}
template <class T>
void dumb_swap(T& a, T& b)
{
std::cout << "dumb_swap\n";
std::swap(a, b);
}
template <class T>
void smart_swap(T& a, T& b)
{
std::cout << "smart_swap\n";
using std::swap;
swap(a, b);
}
int main()
{
zzz::X a, b;
dumb_swap(a, b);
smart_swap(a, b);
int i, j;
dumb_swap(i, j);
smart_swap(i, j);
}
dumb_swap always calls std::swap - even though we'd rather prefer using zzz::swap for zzz::X objects.
smart_swap makes std::swap visible as a fall-back choice (e.g when called with ints), but since it doesn't fully qualify the name, zzz::swap will be used through ADL for zzz::X.
Subjectively, what forces me to use using namespace std; is writing code that uses all kinds of standard function objects, etc.
//copy numbers larger than 1 from stdin to stdout
remove_copy_if(
std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
std::ostream_iterator<int>(std::cout, "\n"),
std::bind2nd(std::less_equal<int>(), 0)
);
IMO, in code like this std:: just makes for line noise.
I wouldn't find using namespace std; a heinous crime in such cases, if it is used in the implementation file (but it can be even restricted to function scope, as in the swap example).
Definitely don't put the using statement in the header files. The reason is that this pollutes the namespace for other headers, which might be included after the offending one, potentially leading to errors in other headers which might not be under your control. (It also adds the surprise factor: people including the file might not be expecting all kinds of names to be visible.)
The ability to refer to members in the std namespace without the need to refer to std::member explicitly. For example:
#include <iostream>
using namespace std;
...
cout << "Hi" << endl;
vs.
#include <iostream>
...
std::cout << "Hi" << std::endl;
You should definitely not say:
using namespace std;
in your C++ headers, because that beats the whole point of using namespaces (doing that would constitute "namespace pollution"). Some useful resources on this topic are the following:
1) stackoverflow thread on Standard convention for using “std”
2) an article by Herb Sutter on Migrating to Namespaces
3) FAQ 27.5 from Marshall Cline's C++ Faq lite.
First of all, this is not required in C - C does not have namespaces. In C++, anything in the std namespace which includes most of the standard library. If you don't do this you have to access the members of the namespace explicitly like so:
std::cout << "I am accessing stdout" << std::endl;
Firstly, the using directive is never required in C since C does not support namespaces at all.
The using directive is never actually required in C++ since any of the items found in the namespace can be accessed directly by prefixing them with std:: instead. So, for example:
using namespace std;
string myString;
is equivalent to:
std::string myString;
Whether or not you choose to use it is a matter of preference, but exposing the entire std namespace to save a few keystrokes is generally considered bad form. An alternative method which only exposes particular items in the namespace is as follows:
using std::string;
string myString;
This allows you to expose only the items in the std namespace that you particularly need, without the risk of unintentionally exposing something you didn't intend to.
Namespaces are a way of wrapping code to avoid confusion and names from conflicting. For example:
File common1.h:
namespace intutils
{
int addNumbers(int a, int b)
{
return a + b;
}
}
Usage file:
#include "common1.h"
int main()
{
int five = 0;
five = addNumbers(2, 3); // Will fail to compile since the function is in a different namespace.
five = intutils::addNumbers(2, 3); // Will compile since you have made explicit which namespace the function is contained within.
using namespace intutils;
five = addNumbers(2, 3); // Will compile because the previous line tells the compiler that if in doubt it should check the "intutils" namespace.
}
So, when you write using namespace std all you are doing is telling the compiler that if in doubt it should look in the std namespace for functions, etc., which it can't find definitions for. This is commonly used in example (and production) code simply because it makes typing common functions, etc. like cout is quicker than having to fully qualify each one as std::cout.
You never have to declare using namespace std; using it is is bad practice and you should use std:: if you don't want to type std:: always you could do something like this in some cases:
using std::cout;
By using std:: you can also tell which part of your program uses the standard library and which doesn't. Which is even more important that there might be conflicts with other functions which get included.
Rgds
Layne
All the files in the C++ standard library declare all of its entities within the std namespace.
e.g: To use cin,cout defined in iostream
Alternatives:
using std::cout;
using std::endl;
cout << "Hello" << endl;
std::cout << "Hello" << std::endl;
Nothing requires you to do -- unless you are implementer of C++ Standard Library and you want to avoid code duplication when declaring header files in both "new" and "old" style:
// cstdio
namespace std
{
// ...
int printf(const char* ...);
// ...
}
.
// stdio.h
#include <cstdio>
using namespace std;
Well, of course example is somewhat contrived (you could equally well use plain <stdio.h> and put it all in std in <cstdio>), but Bjarne Stroustrup shows this example in his The C++ Programming Language.
It's used whenever you're using something that is declared within a namespace. The C++ standard library is declared within the namespace std. Therefore you have to do
using namespace std;
unless you want to specify the namespace when calling functions within another namespace, like so:
std::cout << "cout is declared within the namespace std";
You can read more about it at http://www.cplusplus.com/doc/tutorial/namespaces/.