C++控制台在放置cin.get后关闭

c++ console closing after cin.get is placed

本文关键字:get cin 控制台 C++      更新时间:2023-10-16

我正在编写一个将米转换为英尺的基本程序

// 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;
}

为什么这个 con.get() 不能让控制台保持活动状态?

当您键入数字(如 123 并按回车键)时,输入流中123n。提取到 input 时,123将被删除,n保留在流中。然后,当您调用cin.get()时,将提取此n。它不需要等待任何输入,因为此字符已经在那里等待提取。

因此,一种解决方案是在执行get之前用ignore清除输入流:

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

这将提取并丢弃流中下一个n之前的任何内容。所以如果你的输入是123hellon,它甚至会丢弃hello

另一种方法是使用 std::getline 读取输入行(这也将提取n),然后解析该行以获取输入数字。

因为,它读取最后一个字符,写两次,糟糕的解决方案,所以:

cin.get();

cin.get();

或只是尝试

系统("暂停");

这将释放您的屏幕