Cadel Watson
Cadel Watson

Reputation: 511

C++ cout only prints sometimes

When I run this program and input, for example, the number 7, the final cout command only works occasionally. Otherwise, the program exits successfully but the result is not printed. Why is this happening?

#include <iostream>
#include <cmath>

double treble(double);

int main()
{
    using namespace std;
    cout << "Enter a number:" << endl;

    double numways;
    cin >> numways;

    numways = treble(numways);

    cout << "Your number trebled is: " << numways << endl;

    return 0;
}

double treble(double n)
{
    return n * 3;
}

Upvotes: 0

Views: 1809

Answers (2)

Nihar
Nihar

Reputation: 355

try with this => put

int temp;
cin>>temp;

before return 0; to pause the program, because the execution finished (successfully) before the last output could be written to the console.

Upvotes: 1

nchen24
nchen24

Reputation: 502

You should put using namespace std; outside of all function declarations, right under your #include directives. Also, when you say it's not printing, is it that the console is closing before displaying your result? In that case, I would advocate using a simple cin to "pause" the program. You can do it exactly as @Nihar says, though I might suggest using a string instead of an int so that it doesn't break if you accidentally type something other than an int.

Something like this:

#include <iostream>
#include <cmath>
using namespace std;

double treble(double);

int main(){
    cout << "Enter a number:" << endl;

    double numways;
    cin >> numways;

    numways = treble(numways);

    cout << "Your number trebled is: " << numways << endl;

    string foo;
    cin >> foo;
    return 0;
}

double treble(double n){
    return n * 3;
}

Upvotes: 1

Related Questions