1

I justed started a C++ course & I wrote, compiled, debugged & ran my first program:

// This program calculates how much a little league team spent last year to purchase new baseballs.
#include <iostream>
using namespace std;

int baseballs;
int cost;
int total;
int main()
{
    baseballs, cost, total;

    // Get the number of baseballs were purchased.
    cout << "How many baseballs were purchased? "; 
    cin >> baseballs;

    // Get the cost of baseballs purchased.
    cout << "What was the cost of each baseball purchased? ";
    cin >> cost;

    // Calculate the total.
    total = baseballs * cost;

    // Display the total.
    cout << "The total amount spent $" << total << endl;
    return 0;
}

The only probelm that I encountered was that when I ran the program it failed to display the total amount spent (cout). Could someone please explain why?

Thanks

Jeff H - Sarasota, FL

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
Jeff - FL
  • 11
  • 1

2 Answers2

1

Your program works fine on my system (Mandriva Linux 2010.1 64-bit).

A common issue when developing simple programs doing text I/O in Windows is that the console (cmd.exe) window where they are run will close on its own when the program terminates. That prevents the developer/user from being able to read the program's final output. Perhaps this is what is happening in your case?

EDIT:

Confirmed on Visual Studio 2010. The window closes before you can read the output. You can work around this issue if you either add

system("pause");

or just read an empty input line before the return statement. Keep in mind that the system("pause") "trick" is Windows-specific and I do not recommend it, although it's slightly faster to type.

EDIT 2:

I tried reading an empty input line and I realised that you may actually need to read two such lines, because you already have a remaining newline character in the input buffer that has not been retrieved by the last cin statement.

Community
  • 1
  • 1
thkala
  • 84,049
  • 23
  • 157
  • 201
  • SilverbackNet - so I should highlight the brackets {} in bold? Jim Lewis - I recompiled and ran the program several times. I believe what thkala mentioned: that the cmd.exe window closes before program terminates. It could be the reason why. – Jeff - FL Jan 15 '11 at 18:59
  • @Jeff: Just FYI, StackOverflow has a notification system for comments, triggered by putting an "@" before the person's handle like I've done here. (First 3 characters of the handle is sufficient, I think.) But I'm not sure if multiple notifications in one comment work, so you might want to comment to each person separately. And welcome to SO! – Jim Lewis Jan 15 '11 at 19:09
0

You could add another cin before the return statement to end the program after you view the ouptut. Thkala's logic is correct.