So, I have the following code, and it builds and runs perfectly, tried various values and all is well. You'll notice I use log10 function and I do not include cmath or math.h. Why does it still build and run fine? Are those libraries really needed? Why/Why not? Does it have anything to do with me using visual studio? Like, would it not compile if say I was using a different IDE or command prompt to compile it?
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout << "Classify solutions as acidic or nonacidic" << endl<< endl;
//declaring double molar concentration
double mc = 1;
//using while and if statements to calculate pH in fixed notaion and acidic or nonacidic
while (mc != 0)
{
cout << "Please enter a molar concentration (or enter 0 to exit): ";
cin >> mc;
if (mc != 0)
{
cout << "Molar Conentration = " << scientific << mc << endl; //scientific notation
double pH = -log10(mc);
cout << "pH = " << fixed << setprecision(6) << pH << endl; //6 deciumals
if (pH > 7)
{
cout << "Nonacidic" << endl << endl;
}
else if (pH < 7)
{
cout << "Acidic" << endl << endl;
}
else
cout << "Neutral" << endl << endl;
}
}
//end program when inputing 0
cout << "End of Program" << endl;
return 0;
}
The code:
i = i++ + ++i;
may also compile okay, but that doesn't make it a good idea :-)
It would be wise to include headers for library functions that you use. You don't lose any functionality by doing so but you do guarantee the functionality will work (misuse notwithstanding).
Detailed analysis follows.
Even if an implementation is relaxed about this, the standard mandates it. C++11 17.6.2.2 Headers /3 states:
A translation unit shall include a header only outside of any external declaration or definition, and shall include the header lexically before the first reference in that translation unit to any of the entities declared in that header.
The gcc compiler, for example, will grumble bitterly about your code:
xyzzy.cpp: In function 'int main()':
xyzzy.cpp:22:34: error: 'log10' was not declared in this scope
double pH = -log10(mc);
^
As to why VC++ seemingly violates this rule, it has to do with the fact that header files are allowed to include other header files.
If you compile your code to produce pre-processor output (with /P), you'll find a line buried deep within it thus (at least in VS2013):
#line 1 "c:\\blah\\blah\\vc\\include\\cmath"
And a bit of analysis turns up the following hierarchy of includes:
iostream
istream
ostream
ios
xlocnum
cmath
(<xlocnum>, one of the internal headers used by <locale>, appears to need ldexp() from the <cmath> library, though there may be others as well).
That's further evidenced by the fact that VC++ does complain about the following code:
//#include <iostream>
using namespace std;
int main() {
double oneHundred = 100;
int two = log10 (oneHundred);
return two;
}
with:
error C3861: 'log10': identifier not found
but that error disappears the instant you uncomment the iostream inclusion line.
However, as previously stated, that is not behaviour you should rely on. If you are going to use a library function (or macro/template/whatever), it's up to you to include the correct header.
Otherwise your program compiling correctly is simply an accident.
As you've noticed, the code snippet you provided works in Visual Studio but not with other compilers. This is because of how the standard library is implemented for each compiler.
It turns out that when you include Visual Studio's implementation of <iostream>, you end up including a bunch of other headers indirectly, and one of these headers is <cmath>.
To see the exact chain, navigate to the standard library include directory. For me (I use Visual Studio 2013 Community Edition) this is located at
C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include
Open iostream. Note the line #include <istream>
Open istream. Note the line #include <ostream>
Open ostream. Note the line #include <ios>
Open ios. Note the line #include <xlocnum>
Open xlocnum. Note the line #include <cmath>
Guess what? You included cmath when you included iostream... so your code is good to go, on Visual Studio at least. But, don't rely on implementation details or your code will break if you try to migrate it to another platform/toolchain.
For example, trying to compile the provided snippet using g++ on Cygwin results in the following error:
temp.cpp: In function ‘int main()’:
temp.cpp:22:34: error: ‘log10’ was not declared in this scope
double pH = -log10(mc);
This must mean g++'s implementation of <iostream> doesn't depend on <cmath>
Related
When the following code is compiled I get these errors:
Error C2467 illegal declaration of anonymous 'struct'
C:\Program Files (x86)\Windows Kits\10\Include\10.0.18362.0\um\winnt.h 12723
Error C2133 '_IMAGE_POLICY_METADATA::Policies': unknown size
C:\Program Files (x86)\Windows Kits\10\Include\10.0.18362.0\um\winnt.h 20801
Error C2467 illegal declaration of anonymous 'struct'
C:\Program Files (x86)\Windows Kits\10\Include\10.0.18362.0\um\winioctl.h 4327
The code:
#include <iostream>
#include <chrono>
#include <thread>
#include <windows.h>
using namespace std;
int main()
{
std::cout << "Timer!\n Enter a number of seconds: \n";
int n;
std::cin >> n;
std::this_thread::sleep_for(std::chrono::milliseconds(n*1000));
std::cout << "Timer is up";
std::cout << '\a';
return 0;
}
These errors do not occur when windows.h is removed, as I am somewhat new I could be making a basic mistake however a lot of tutorials use it and it simply does not want to work. I have used a very basic snippet of code so that it is easier to determine whether it is a mistake on my behalf or an error somewhere else.
Windows 10, Visual Studio 2019 16.2.5
As #FrançoisAndrieux mentions in the comments, the windows.h header requires not enabling the "Disable Language Extensions" option under C/C++ -> Language (switch /Za).
However, if you are only looking to compile simple code that does not require windows.h, simply remove it. You can write:
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
std::cout << "Timer!\n Enter a number of seconds: \n";
int n;
std::cin >> n;
std::this_thread::sleep_for(std::chrono::milliseconds(n*1000));
std::cout << "Timer is up\a";
return 0;
}
Both of the two error descriptions are related to that switch which is as #Acorn said. The link below is Microsoft's official document. If you can't solve your problem in this way. Maybe you need to consider using VS tool to repair your environment.
https://learn.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-error-c2467?view=vs-2015
https://learn.microsoft.com/en-us/cpp/error-messages/compiler-errors-1/compiler-error-c2133?view=vs-2015
#include <istream> //Includes the input/output library
using namespace std; // Makes std features available
// The main function of the program
// It outputs the greeting to the screen
int main() {
count <<"Hello World! I am C++ Program." <<endl;
return 0;
}
IntelliSense: no operator message Line 7, Column 8
error C2563:mismatch in formal parameter list Line 7, Column 1
Replace #include <istream> with the correct header, #include <iostream>.
Helpful mnemonic:
io = input/output
stream = "stream of data"
Additionally, the name of the standard output stream is std::cout or cout with the std:: namespace scope removed.
Helpful mnemonic:
std:: = Standard library's
cout = console output
The problems you are having with your simple block of code is simply: spelling errors.
Firstly, you have misspelled the input/output stream file in your include statement, so you need to rename the header file to:
#include <iostream>
There is no heade file named istream.
Secondly, you also misspelled the cout function to count. Change that line to:
cout << "Hello World! I am C++ Program." << endl;
Those lines should work now.
Also a recommendation for your future programs; avoid using the line
using namespace std;
Why? Because as you move on to more complex programming, you will undoubtedly learn and begin to define a data type or variable, and sometimes, that name may also be used by the standard library. As a result, you will have a hard time trying to differentiate the variables or data types you defined and the ones defined in the std library.
Therefore, try and attach std:: before every function that is a part of the standard library.
EDIT:
The code you posted in the comments box is pretty unreadable, so I just fixed it and have posted it below:
#include <iostream> //Includes the input/output library
using namespace std; // Makes std features available
// The main function of the program
// It outputs the greeting to the screen
int main()
{
cout <<"Hello World! I am C++ Program." <<endl;
return 0;
}
I've tried this in my IDE and fixed with the same and only recommendations from above. It works for me.
#include <iostream>
#include <iomanip>
int main ()
{
long double price;
std::cout << "Please, enter the price: ";
std::cin >> std::get_money(price);
if (std::cin.fail()) std::cout << "Error reading price\n";
else std::cout << "The price entered is: " << price << '\n';
return 0;
}
I am getting error forlling error while compiling the above program.
getmoney.cpp: In function int main()':
getmoney.cpp:10: error:get_money' is not a member of `std'.
get_money is the predefined function. I don't know why i am receiving this error.
If you included iomanipbut nevertheless the compiler issues an error it means that your compiler does not support C++ 2011 standard or you did not select such an option of the compiler.
Did you include the header "iomanip" in your code?
Wen you have such problem go to check on a reference website such as http://www.cplusplus.com/reference/iomanip/get_money/
and you will see that
This manipulator is declared in header <iomanip>.
and you even often have an example code which show you how to use it.
So including iomanip may solve your problem
If that is not working, you are probably using an older compiler which does not support C++ 11. And therefore you could simply not use this function without changing your compiler.
I am new to C++ programming.
So I was trying my luck executing some small programs.
I am working on HP-UX which has a compiler whose
executable is named aCC.
I am trying to execute a small program
#include <iostream.h>
using namespace std;
class myclass {
public:
int i, j, k;
};
int main()
{
myclass a, b;
a.i = 100;
a.j = 4;
a.k = a.i * a.j;
b.k = 12;
cout << a.k << " " << b.k;
return 0;
}
When I compile this it gives me an error:
> aCC temp.cpp
Error 697: "temp.cpp", line 2 # Only namespace names are valid here.
using namespace std;
^^^
What exactly is the problem?
Is std not considered as a namespace in the aCC compiler or is there some serious drawback with aCC?
If I change the <iostream.h> to <iostream>, I get some more errors added as below.
>aCC temp.cpp
Error 112: "temp.cpp", line 1 # Include file <iostream> not found.
#include <iostream>
^^^^^^^^^^
Error 697: "temp.cpp", line 2 # Only namespace names are valid here.
using namespace std;
^^^
Error 172: "temp.cpp", line 14 # Undeclared variable 'cout'.
cout << a.k << " " << b.k;
Which version of aCC are you using? Older versions used a pre-standard STL implemenntation that put everything in the global namespace (i.e. didn't use the std namespace)
You might also need to use the -AA option when compiling. This tells the compiler to use the newer 2.x version of HP's STL library.
>aCC -AA temp.cpp
And it should always be
<iostream>
<iostream.h>
is from a pre-standard implementation of the language, though it is usually shipped so as to maintain backwards compatibility with older code.
Try with:
#include <iostream>
Instead of:
#include <iostream.h>
iostream.h is an old style header in which all functions are exposed in global namespace. naturally in such a case, using namespace std may not work since std namespace is probably not exposed by iostream.h header (in this compiler). As explained above, try with # include which is a new style C++ standard library header. (thanks Shailesh Kumar for the comment! included it in the answer).
I'm trying to run my very first c++ program in linux (linux mint 8). I use either gcc or g++, both with the same problem: the compiler does not find the library I am trying to import.
I suspect something like I should either copy the iostream.h file (which I don't know where to look for) in the working folder, move my file to compile somewhere else or use an option of some sort.
Thanks for your suggestions.
Here's the gcc command, the c++ code, and the error message:
gcc -o addition listing2.5.c
.
#include <iostream.h>
int Addition(int a, int b)
{
return (a + b);
}
int main()
{
cout << "Resultat : " << Addition(2, 4) << "\n";
return 0;
}
.
listing2.5.c:1:22: error: iostream.h: No such file or directory
listing2.5.c: In function ‘main’:
listing2.5.c:10: error: ‘cout’ undeclared (first use in this function)
listing2.5.c:10: error: (Each undeclared identifier is reported only once
listing2.5.c:10: error: for each function it appears in.)
Now the code compiles, but I cannot run it from the command line using the file name. addition: command not found Any suggestion?
cout is defined in the std:: namespace, you need to use std::cout instead of just cout.
You should also use #include <iostream> not the old iostream.h
use g++ to compile C++ programs, it'll link in the standard c++ library. gcc will not. gcc will also compile your code as C code if you give it a .c suffix. Give your files a .cpp suffix.
please use g++ not gcc to compile it
You need <iostream> not <iostream.h>.
They are also header files not libraries.
Other things to fix, cout should be std::cout and you should use std::endl instead of "\n".
You need <iostream>, <iostream.h> is non-standard too-old header. Try this:
#include <iostream>
int Addition(int a, int b)
{
return (a + b);
}
int main()
{
using namespace std;
cout << "Resultat : " << Addition(2, 4) << "\n";
return 0;
}
If you don't want to use std alongside cout as below-
std::cout << "Hello World";
You can also define std at beginning of program by 'using namespace' keywords as-
#include <iostream >
using namespace std;
int Addition(int a, int b)
{
return (a + b);
}
int main()
{
cout << "Result : " << Addition(2, 4) << "\n";
return 0;
}
Now you need not to write std,everytime you use I/O operations.