C++ - Need help (something simple)
Hello, Im just starting to learn c++. Im just having one problem: I am making a simple calculator, but when I enter (lets say) 5 and 9 than hit enter cmd goes away! How do I prevent this?
Here is the source code:
using namespace std;
int main()
{
int length;
int width;
cout << "Enter the length: ";
cin >> length;
cout << "Enter the width: ";
cin >> width;
cout << "The area is ";
cout << length * width;
cin.get();
return 0;
}```
Program: http://d01.megashares.com/?d01=961c08c
I have cin.get(); in there so I don't know the problem!
If somebody could help, I would love it:)!
Thanks,
hotfoot
hotfoot wrote: Hello, Im just starting to learn c++. Im just having one problem: I am making a simple calculator, but when I enter (lets say) 5 and 9 than hit enter cmd goes away! How do I prevent this?
Here is the source code:
using namespace std;
int main()
{
int length;
int width;
cout << "Enter the length: ";
cin >> length;
cout << "Enter the width: ";
cin >> width;
cin.ignore();
cout << "The area is ";
cout << length * width;
cin.get();
return 0;
}```
should help if it dont work then try optimizing your code. ( such as changing length to x ) and taking bits out. always helps me.
cin.ignore(); is a function that reads and discards a character. when you type input into a program, it takes the enter key too. We don't need this, so we throw it away. Keep in mind that the variable was declared an integer; if the user attempts to type in a decimal number, it will be truncated (that is, the decimal component of the number will be ignored)
nattie wrote: cin.ignore(); is a function that reads and discards a character. when you type input into a program, it takes the enter key too. We don't need this, so we throw it away. Keep in mind that the variable was declared an integer; if the user attempts to type in a decimal number, it will be truncated (that is, the decimal component of the number will be ignored) Thank you!!!
- hotfoot982
chislam wrote: are you simply double clicking your exe, or are you cd'ing to it via cmd? If you are doing the first method, then add
system("pause");
after you print to the screen the values. This will bring up the original "Hit any key to Continue…" and will exit when you hit enter, etc.
a classic read before posting, they dont read the whole thread before postingi already told him to put in cin.ignore();.