Hi All,

I have written a small interactive console application to help me understand variables, when you run the application it will ask you for a length and a width and it is supposed to work out the area.

It works up to the part were it is supposed to give you the answer.

I can't see were I have gone wrong can anyone give me a clue.

#include <iostream>
using namespace std;

int main()
{
int length; // this declairs a variable
int width; // this declairs another variable

cout <<"Enter The Length: ";
cin >> length; //input the length

cout << "Enter The Width: ";
cin >> width; //input the width

cout <<"The area is: ";
cout << length * width; //display the area

cin.get();

return 0;
}

Thanks very much

John

There are left over characters in the stream that cin.get() is reading immediately. It is not blocking, so the program ends immediately and I assume the window is closing so you cannot see the output. Try this:

#include <iostream>
using namespace std;

int main()
{
    int length; // this declairs a variable
    int width; // this declairs another variable

    cout <<"Enter The Length: ";
    cin >> length; //input the length

    cout << "Enter The Width: ";
    cin >> width; //input the width

    cout <<"The area is: ";
    cout << length * width; //display the area

    cin.ignore(1024, '\n');
    cin.get();

    return 0;
}

I added the cin.ignore(1024, '\n'); line. 1024 is an arbitrary large value because I did not want to scare you with the more correct numeric_limits<> construction. ;)

My bet is that the window is closing before you have a chance to see the output. The reason is that when you enter numeric data the program will leave the Enter key '\n' in the keyboard buffer, and when cin.get() is called it just retrieves it. When you need to do is flush that out of the buffer. Add cin.ignore(); after cin >> width; [edit] What ^^^ Tom said :) [/edit]

Thanks for the help everyone, I will give this a try tommorow afternoon.

Thanks again

John

Code works a treat everyone, thanks very much for your help.

John

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.