Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cout doesn't display anything in terminal

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!!

like image 801
John Spencer Avatar asked Aug 30 '13 15:08

John Spencer


People also ask

Why is cout not printing anything?

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 is my C++ program not showing output?

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.

Is cout a command in C++?

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(<<).

What library do you need for cout?

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.


1 Answers

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.

like image 129
BoBTFish Avatar answered Sep 25 '22 00:09

BoBTFish