I'm just trying to get my c++ code to output properly in terminal on my mac, but it doesn't show anything. I'm using xcode as a text editor, saving the file as Code.cpp, and then typing g++ Code.cpp into terminal. Before it was showing errors when my code had bugs, but now that it runs correctly it doesn't show any output. Any thoughts? Here's my code:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World" << endl;
return 0;
}
Here's what I put into terminal, and it just skips down to the next line without the "Hello World" output.
jspencer$ g++ Code.cpp
jspencer$
Thanks in advance for the help!!
This may happen because std::cout is writing to output buffer which is waiting to be flushed. If no flushing occurs nothing will print. So you may have to flush the buffer manually by doing the following: std::cout.
Why this C++ code not showing any output? There is not much outputs in this code. You can add some check point outputs (some outputs at strategic points in code to get a print every time execution cross such a point) to get an idea of what your code is doing, or turn to debugger.
The C++ cout statement is the instance of the ostream class. It is used to produce output on the standard output device which is usually the display screen. The data needed to be displayed on the screen is inserted in the standard output stream (cout) using the insertion operator(<<).
The cout command is a data stream which is attached to screen output and is used to print to the screen, it is part of the iostream library.
g++
is a compiler. It turns your source code into an executable program, but doesn't run it.
You must run the program yourself. The default name of the program generated by g++
is a.out
(for historical reasons), so you would run it as
$ ./a.out
If you want to choose a different name for your program, you use the -o
option:
$ g++ Code.cpp -o myProgram
$ ./myProgram
But here's how I would write your program:
#include <iostream>
int main() {
std::cout << "Hello World\n";
return 0;
}
See here and here for some reasons.
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