开发者

console program exits [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to stop C++ console application from exiting immediately?

I have the following console program:

#include <iostream>
using namespace std;

int main()
{
    int a;
    int b;


cout<<"Enter a";
cin>>a;

cout<<"Enter b";
cin>&g开发者_开发问答t;b;

int result = a*b;

cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl;
    return 0;
}

Once i run the program,it accepts the input but exits before i can have a look at the results.What do i need to do for the program not to exit before i can take a look at the results?.


BTW, you've already calculated the value of result before you've gotten your input for a and b, so the value of result will either be 0 if your compiler assembles code that zero-initializes any variables declared on the stack, or will just be some random value. In fact, you really don't need to even declare result ... you can calculate it's value in the cout statement. So you can adjust your last line so it looks like this:

cout << "You entered" << a <<"and you entered"<< b 
     << "Their product is" << (a*b) << endl;

To stop the program from exiting, you can grab another char from stdin. So you can do the following:

cout << "Press any key to exit..." << endl;
char extra;
cin >> extra;


What about adding system ("pause"); before return 0; statement?


Use getche() ,getch() or any character based input function.

int main()
{
    int a;
    int b;
    int result = a*b;

cout<<"Enter a";
cin>>a;

cout<<"Enter b";
cin>>b;

cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl;
getch(); //use this.It would wait for  a character to input.
return 0;
}

And generally we use Enter to exit the program whose ASCII value is fetched by it .But since it is of no use to us not storing it in a variable.


You could ask for more feedback

cout<<"You entered"<<a<<"and you entered"<<b<<"Their product is"<<result<<endl;

char stop;
cin >> stop;


I like to use getch() from conio.h when I'm on Windows, but that's not quite portable :/


Windows:

//1
    system ("pause");
//2
    #include<conio.h>
    _getch();

.NET (Windows):

System::Console::ReadLine();

Overall:

    #include <cstdlib.h>
    return EXIT_SUCCESS;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜