user2699451
user2699451

Reputation:

c++ console closing after cin.get is placed

i am writing a basic program to convert meters to feet

// TestApp.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
# include <iostream>


int main()
{
    using namespace std;

    double feet;
    short int input;
    const double feettometer = 3.28 ; (changed after second comment, small mistake)

    cout << "Enter meter value: ";
    cin >> input;

    feet = feettometer * input ;

    cout << "your meter value of " << input << " in feet is " << feet ;
    cin.get();

    return 0;
}

why does this con.get() not keep the console alive?

Upvotes: 2

Views: 702

Answers (2)

kjhkjhkjh
kjhkjhkjh

Reputation: 410

because, it reads last character, write it twice, bad solution so:

cin.get();

cin.get();

or Just try

System("pause");

which will free your screen

Upvotes: -1

Joseph Mansfield
Joseph Mansfield

Reputation: 110668

When you type in a number like 123 and hit enter, the input stream has 123\n in it. When you extract into input, 123 is removed and \n is left in the stream. Then when you call cin.get(), this \n is extracted. It doesn't need to wait for any input because this character is already there waiting to be extracted.

So one solution is to clear the input stream with ignore before doing get:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

This will extract and discard anything up to and including the next \n in the stream. So if your input was 123hello\n, it would even discard the hello.

An alternative would be to read the input line using std::getline (which will extract the \n too) and then parse the line for the input number.

Upvotes: 8

Related Questions