简体   繁体   中英

Why doesn't the cout command print a message?

#include <iostream>
using namespace std;

int main()
{
int x = 42;
cout << x; // This line doesn't print! Why?
    return 0;
}

Screenshot of Visual C++: http://bildr.no/image/ZlVBV0k0.jpeg

This code gives me nothing but a black console window that flashes by when I click on debug. Isn't the number 42 supposed to be printed in the console window? This is my first application in C++. I have experience in C# from high school.

EDIT:

Now I have tried this code:

// Primtallsgenerator.cpp : Defines the entry point for the console application.
//

#include <iostream>
using namespace std;

int main()
{
int x = 42;
cout << x << endl; // This line doesn't print! Why?
cin >> x;
    return 0;
}

It still doesn't work. Screenshot of the code here: http://bildr.no/image/ODNRc3lG.jpeg

The black windows still just flashes by...

It did print the message, it was just too fast for you to see.

add this command:

cin >> x;

or this one

while(true) {}

before the return statement.

Yes, it will print the number. Then the program ends, and the console window is closed. Run it in the debugger, and put a breakpoint on the return 0; line. Then you'll see it.

Two things to note:

First, you are not forcing the buffer to flush, so there is no guarantee the output is being sent to the screen before the program ends. Change your cout statement to:

cout << x << endl;

Second, Visual Studio will close the console when it ends (in Debugging mode). If you do not debug it (Ctrl-F5 by default), it will keep the console open until you press a key. This will allow you to see the output. Alternatively, you can add a cin.get() before your return statement which will force the program to wait for a character to be in the input stream before the program is allowed to exit.

This code should work fine:

#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
    int x = 42;
    cout << x; 

    getchar();
    return 0;
}

Also check this documentation about getchar() .

I recommend to use system pause at the end before the "return 0" statement like this:

system("PAUSE");

This is cleaner and much more effective.

If you are working with a console application in Visual Studio, you have to go to your project's linker properties and set your SubSystem setting to CONSOLE .

And get a habit of running your code without a debugger (Ctrl+F5 by default) when you don't need the debugger. That way the console window will not flash and disappear by itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM