why does not eclips know cout and cin in my code? - c++

I am new in c++, I want to write my program with eclips but it does not know cout and cin however I add include
This is my code:
class READY {
public:
READY();
virtual ~READY();
#include <iostream.h>
int main (){
cout<<"hello";
}
};
#endif /* READY_H_ */

Move the include and main outside the class and qualify cout with std:::
#include <iostream>
class READY {
public:
READY();
virtual ~READY();
};
int main (){
std::cout<<"hello";
}
C++ is not Java, main resides at the global scope, not as a class member.
Also, it's <iostream>, not <iostream.h>.
Whatever tutorial or book you're following... it isn't any good.

You need to put that #include at the top of your file; including headers in the middle of a class will do weird, weird things! At the very least, it will embed all the names in the header into your class; most likely, it will simply fail to compile.
Furthermore, modern C++ puts cout and essentially every other symbol defined in the standard library into a namespace named std, so you need to write std::cout, or put "using namespace std;" before your class definition, but after the #include.

There are a couple of problems with your code:
The #include statement has to be outside the class declaration. It is good practise to put those at the top of the file and not scatter them through the file as it makes it much easier to check for dependencies in your code by eyeballing the top of the file instead of searching the whole file for #includes.
Your main() function also has to be declared and defined outside the class. In contrast to Jave, main() in C and C++ is a standalone function.
As mentioned, cin and cout live in the std namespace. I would recommend referring to them with the fully qualified name (ie, std::cin and std::cout), although you can use using std::cin; and using std::cout; either inside the function or in your implementation file after all includes
You are including iostream.h - that is the "wrong" file as that is for the old iostreams library. The correct include for the standard compliant iostreams is <iostream>

Related

Undefined reference to a defined method

So I was trying to access a method that is defined in another class and has the prototype in the header. I'm pretty positive I defined it but it keeps popping up undefined reference to SafeCracker.
Main.cpp
#include <iostream>
#include "mystuff.h"
using namespace std;
void BigDog(int KibblesCount);
int main()
{
cout << SafeCracker(1);
return 0;
}
mystuff.cpp
#include <iostream>
using namespace std;
string SafeCracker(int SafeID)
{
return "123456";
}
mystuff.h
using namespace std;
#ifndef MYSTUFF_H_INCLUDED
#define MYSTUFF_H_INCLUDED
string SafeCracker(int SafeID);
#endif // MYSTUFF_H_INCLUDED
Here it tells you that you have an undefined reference, so you don't really have a problem with the prototype.
Had you forgotten to include the header file that contains the prototype you would have gotten something like
main.cpp: In function ‘int main()’:
main.cpp:8:13: error: ‘SafeCracker’ was not declared in this scope
cout << SafeCracker(1);
Your undefined reference is a linker error. The most likely cause would be that you did not use mystuff.cpp when compiling
If you're compiling from the command line, you should give both files as parameters.
If you're using an IDE that calls the compiler, make sure that the file is part of the project.
For example in Code::Blocks right-click on the file name and go "add to project" (If I remember correctly)
It is also possible that you made a typo in the function declaration in mystuff.cpp (that doesn't seem to be the case here though)
Now there is one important thing about your code you should take note of:
It is very bad practice to put a using namespace in a header file.
using namespace std; in a .cpp source file is mostly up to you, and that using statement will only apply to that particular file.
But if you put it in a header file that is meant to be included through #include , the using there will be forced upon any code that includes it.
Here is an example:
main.cpp
#include <iostream>
// including mystuff.h to use that awesome SafeCracker()
#include "mystuff.h"
// I need to use an std::map (basically an associative array)
#include <map>
// the map of my game
class map
{
int tiles[10][10];
};
int main()
{
// The std map I need to use
std::map<int, int> mymappedcontainer;
// The map of my game I need to use
map mytiles;
// The reason why I need to include mystuff.h
cout << SafeCracker(1);
return 0;
}
Normally, my class map should not be a problem since the map I included from the standard library is inside the namespace std, so to use it you would need to go std::map.
The problem here is that, since mystuff.h has using namespace std; in it, the symbol map is already used, and that creates a conflict.
You do not now who will use your header files, or if you will use them again a long time from now, and maybe then you will want to use name that is already used in the std namespace.
I advise you to use std:: before things taken from the standard libraries instead (std::string instead of just string for example)
PS: In C++, "class" refers to a class data structure, and the functions you made here are not part of any class. You should say "defined in another file" or "defined in another translation unit" instead

C++ compilling errors when using Quadprog++ with Eigen together

this is my first question here, I've searched it all over for a long time yet no solution.
I'm using QUadprog++ to solve a quadratic problem. When I use it in a test alone, it was alright. But when I implement it into my project, which contains Eigen, the Eigen operations will have errors like "Matrix A has no member named ‘lu_inverse’". If I comment the header files of Quadprog++ (Array.hh and Quadprog++.hh) out, the errors just disappear. So I assume that it was a conflict error between the header files of Eigen and Quadprog++. Does anyone have some clue? Thanks in advance!
You can also switch to one of QuadProgpp versions which can work with Eigen types directly: https://github.com/asherikov/QuadProgpp, https://www.cs.cmu.edu/~bstephe1/eiquadprog.hpp; or try an alternative implementation of the same algorithm (also Eigen based) https://github.com/asherikov/qpmad.
if your using namespace quadprogpp; then dont. your different libraries have the same typenames and thats causing the errors you have. It may be a few more characters to type quadprogpp::someFunction(); but its worth it. This is also why you shouldn't ever put a using namespace in a header ever. Its because you pollute all files that include that header with the namespace symbols and name conflicts can ensue which is the same kind of error your having right now.
the Quadprog library is in it's own namespace.
#if !defined(_ARRAY_HH)
#define _ARRAY_HH
#include <set>
#include <stdexcept>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
namespace quadprogpp {
enum MType { DIAG };
template <typename T>
class Vector
notice how just after the #includes there is a decleration of namespace quadprogpp{} and everything that is defined in its enclosing brackets will be defined in scope to quadprogpp, so to use any of this library you have to prefix eveything with the namespace name. this is no different than using things from the standard library. I'm quite sure you've written the standard c++ hello world
#include<iostream>
int main()
{
std::cout << "hello world!" << std::endl;
return 0;
}
cout and endl being part of namespace std have to be prefixed with std:: to access them. Many new programmers to c++ dislike this and one of the very first things they google is how to not have to type out namespaces.
#include<iostream>
using namespace std;
int main()
{
cout << "hello world" << endl;
return 0;
}
the next thing new programmers often do is learn to place their definitions in header files and their program logic in cpp files. Thats when they commit the next common mistake.
#ifndef MYHEADER
#define MYHEADER
#include<string>
#include<vector>
#include<iostream>
using namespace std; //Never do this in a header.
doing that pollutes all of your code with everything in the standard library. That may seem like a trivial thing but when you start using another library or perhaps you create your own type that has the same name as things in the standard library that causes name collisions.
That's when the compiler simply cant reason about which Vector you want. But both Quadprog.hh and Array.hh in Quadprog++ are wrapped in namespace quadprogpp to specifically prevent name collision, which is the whole purpose of namespaces. So there is somewhere in your code, likely a header file, where you've made the statement of using namespace quadprogpp;, or some other namespace that defines an Array type, and the compiler can't deduce which type your referring to in your code.
Other than removing your using namespace statements you can also prefix a typename with its namespace qualifer to disambiguate which type your talking about. In your case I'm confident your Array should be declared as quadprogpp::Array arraynamme; rather than simply Array arrayname;

why should i include the header file <iostream> after using the namespace std?

Since the namespace std already has the c++ libraries that contain the function definitions(if i am right), then why do we include header files on top of it??. Since namespace std includes the c++ standard libraries, I don't see a reason to include the declarations of it separately.
When you do #include <iostream> it causes a set of classes and other things to be included in your source file. For iostream, and most of the standard library headers, they place these things in a namespace named std.
So the code for #include <iostream> looks something like this:
namespace std {
class cin { ... };
class cout { ... };
class cerr { ... };
class clog { ... };
...
}
So at this point, you could write a program that looks like:
#include <iostream>
int main() {
std::cout << "hello\n";
return 0;
}
Now, some people feel that std::cout is too verbose. So they do:
#include <iostream>
using namespace std;
int main() {
cout << "hello\n";
return 0;
}
Personally, I'd recommend against this, and if you really feel that std::cout is too verbose, then I'd suggest that you use a smaller using statement.
#include <iostream>
using std::cout;
int main() {
cout << "hello\n";
return 0;
}
If you're wondering why I would recommend against using namespace std, then I would forward you to the following two other posts on stackoverflow:
C++ Distance Function Keeps Returning -1
Why is "using namespace std" considered bad practice?
The compiler itself does not have the definitions of the things that are in any namespace (whether it is std or some other namespace). That is the role of source files and header files.
What using namespace std; tells the compiler is that "If you can't find some name in the current namespace, go look in the std namespace as well".
What #include <iostream> tells the compiler is that you want the contents of the header called iostream to be included in your sources. This will provide the compiler with code to do cin, cout and a lot of other related functionality. The content of this file is declared like namespace std { ... all the stuff goes here ... }.
The usage of namespace allows someone else, working in namespace math; to not have to worry about "Hmm, what do I do now, I need a counter for number of entrances, let's call it cin - but hang on, is that ever used anywhere?".
This may not be the greatest of examples, but in large projects, it gets increasingly hard to keep track of things and what names they have. And C++ is a language intended for large projects of millions of lines of code - and now it starts getting hard to remember if you've used a particular name or not. Namespaces make sure that you don't have to worry about it outside of a particular namespace.
(Oh, and in my code, I tend to not use using namespace std;, but write std::cout << "Hello, World!" << std::endl; - this helps to make it clear that the cout I'm using here is the std one, and not something else. This is particularly useful when you have several namespaces with similar things, like in my own compiler, where I have my compiler with it's functionality, the std namespace providing some things, and llvm compiler things - if I were to stick using namespace llvm; at the beginning of the code, it would be very hard to track whether Type* p = ...; is from LLVM or some part of my own code.)
...why do we include header files on top of it???
Yes, there is some big confusion here.
Namespaces
Namespaces are a method to categorize or group together, symbols such as function names.
Namespaces are design to prevent name conflicts between different software components, such as libraries.
Functions that are a part of the standard language, are grouped under the namespace std.
The C++ language provides statements to reduce the amount of typing when using namespaces. One of these is the using statement.
Header (include) Files
When you write a program, the compiler is not required to automatically include all the symbol definitions, such a function declarations. You need to tell it which functions you plan on using.
For example, I could write a program without using the sort or advance functions from the algorithm group. Therefore I would not include the header file algorithm.
The C++ language is designed to be "use what you need", in other words, we can create small programs by only including the functions we need.
Other Platforms
By the way, there are many other platforms out there than the one you are using.
Some platforms need to fit in small memory areas and may not have a keyboard or display (such as embedded controllers).
So remember, C++ was defined to support platforms from the small and constrained to the large and virtually unconstrained system.
Thus the requirement to "include only what you need" theme.
Summary
In summary, since the C++ languages doesn't automatically, magically, provide the definitions of the entire library, including the template library, you need to tell the compiler which groups of functions you want to use. This allows for quicker compilations since only the required header files are specified.
Note: Some shops and library supplies like to use the Monolith include system. This means that they have one include file that includes their entire library, whether you use one function or many. The windows.h is a classic example. One detriment is that when one header file is changed, everything needs to be rebuilt. With separated include files, only the components that include the changed header file need to be rebuilt.
Use of preprocessor directive #include is as old as c++ itself. And its not going away any sooner.In C++ namespace Doesn't import anything into your program, it just defines the scope of your particular header file's function.So, both are required. Click hereto understand why use namespace.
Your question is: namespace std has all the definitions of functions/classes of iostream library. So simply using using namespace std is enough to call or use cout or all other functionalities of iostream library. Why do we have to use line #include <iostream>? It seems redundant.
Roughly we can think that iostream library has two files: header and implementation/source file. These two files have a namespace called std. The header file only contains the declarations or forward declarations of classes or functions or variables that iostream library is going to use and these declarations or forward declarations are under the std namespace. The implementation file contains the actual implementations of the classes or functions or variables and these implementations are under the std namespace; this file is also called the source file.
So if you only use using namespace std without #include <iostream> in your main.cpp file compiler will search std namespace in your main.cpp file, but it is not here. You will get compiler error.
Now if you include this #include <iostream> line in your main.cpp, preprocessor will go iostream's header file and copy the std namespace along with its code into our main.cpp. And linker will link the precompiled(as iostream is a SLT so it comes with compiler with prebuilt) source/implementation file of iostream to your main.cpp. Now to use functions or variables of iostream that sit under std namespace in main.cpp we have to use scope resolution operator(::) to tell the compiler that cout, cin and other functionalities of iostream sit at std namespace. Thus we simply write like this: std::cin, and std::cout.
Now typing std:: seems redundant to some people so they tell the compiler by using this using namespace std "Hey compiler, if you don't find any variables/functions/classes in global/current namespace go look in the std namespace." Though this is not the best practice but that is another topic to discuss. Therefore your assumption that std namespace contains all the definitions of all SLT's functions/classes/variables of C++ is not correct in most cases, but std namespace only contains the declaration from STL is the correct assumption.
Here is a dummy implementation how iostream libray is added to our code files:
iostream.h:
// This is header file that only contains the
// functions declarations.
namespace std_dum
{
int add(int x, int y);
int mult(int x, int y);
}
iostream_dum.cpp:
// This is source file of iostream_dum.h header
// which contains the implementation of functions.
#include "iostream_dum.h"
namespace std_dum
{
int add(int x, int y)
{
return x + y;
}
int mult(int x, int y)
{
return x * y;
}
}
main.cpp :
#include <iostream>
#include "iostream_dum.h"
int main()
{
std::cout << std_dum::add(100, 200) << '\n';
std::cout << std_dum::mult(100, 200) << '\n';
return 0;
}
To see what happens to our main.cpp file after preprocessing run this command: g++ -E main.cpp iostream_dum.cpp.
Here is roughly our main.cpp looks like:
namespace std_dum
{
int add(int x, int y);
int mult(int x, int y);
}
int main()
{
std::cout << std_dum::add(100, 200) << '\n';
std::cout << std_dum::mult(100, 200) << '\n';
return 0;
}
namespace std_dum
{
int add(int x, int y)
{
return x + y;
}
int mult(int x, int y)
{
return x * y;
}
}
For the sake of clarity, I discarded all the codes that the preprocessor copied from #include <iostream>.
Now it should be pretty clear.

What is the relationship between iostream and namespace std?

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

include and using namespace in C++

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.