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开发者_StackOverflow社区 << "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
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.
You could add another cin before the return statement to end the program after you view the ouptut. Thkala's logic is correct.
精彩评论