在继续之前,Cin不会让用户在控制台中输入任何内容

时间:2016-02-09 00:30:25

标签: c++ cin

我只是想让用户在每个检查站输入他们的比赛时间(以分钟为单位)。当我尝试在控制台中运行时,它会跳过用户的所有输入,但名称除外。

#include <iostream>
#include <cmath>
#include <string>

using namespace std;


int main(void)

{

  int RacerName;
  int CheckpointOne;
  int CheckpointTwo;
  int CheckpointThree;
  int CheckpointFour;

  cout << "Enter the racer's first name: ";
  cin >> RacerName;

  cout << "Enter the time (in minutes) at checkpoint 1: ";
  cin >> CheckpointOne;
  cout << "\nEnter the time (in minutes) at checkpoint 2: ";
  cin >> CheckpointTwo;
  cout << "\nEnter the time (in minutes) at checkpoint 3: ";
  cin >> CheckpointThree;
  cout << "\nEnter the time (in minutes) at checkpoint 4: ";
  cin >> CheckpointFour;

  return 0;
}

2 个答案:

答案 0 :(得分:2)

RacerName应该是string,而不是int

string RacerName;

当您键入非整数以响应该提示时,转换将失败。所有其他cin行都会发生同样的情况,因为它会留下您在输入缓冲区中输入的名称,并且每个行都试图将其转换为数字。

DEMO

答案 1 :(得分:0)

Barmar纠正了您的问题,但您遇到的主要问题是您没有检查以确保您的输入成功。您可以通过稍微修改代码来实现:

#include <iostream>
#include <limits>
#include <string>

// These 2 functions will read a string/integer from an istream with error checking
std::string ReadString(std::istream& is)
{
    std::string result = "";
    while (!std::getline(is, result)) // do this until the user enters valid input
    {
        std::cin.clear(); // clear the error flags
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore the invalid data
    }
    return result;
}

int ReadInt(std::istream& is)
{
    int result = -1;
    while (!(is >> result))
    {
        std::cin.clear(); // clear the error flags
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore the invalid data
    }
    return result;
}

int main(void)
{
    std::cout << "Enter the racer's first name: ";
    std::string RacerName = ReadString(std::cin); // NOTE:  should be a string

    std::cout << "Enter the time (in minutes) at checkpoint 1: ";
    int CheckpointOne = ReadInt(std::cin);
    std::cout << "\nEnter the time (in minutes) at checkpoint 2: ";
    int CheckpointTwo = ReadInt(std::cin);
    std::cout << "\nEnter the time (in minutes) at checkpoint 3: ";
    int CheckpointThree = ReadInt(std::cin);
    std::cout << "\nEnter the time (in minutes) at checkpoint 4: ";
    int CheckpointFour = ReadInt(std::cin);

    std::cout << "\nTimes for " << RacerName << std::endl
            << "\tCheckpoint 1:  " << CheckpointOne << std::endl
            << "\tCheckpoint 2:  " << CheckpointTwo << std::endl
            << "\tCheckpoint 3:  " << CheckpointThree << std::endl
            << "\tCheckpoint 4:  " << CheckpointFour << std::endl;
    return 0;
}

注意2个实用功能。他们都会检查以确保正确读入输入。如果输入失败,它将清除错误标志并忽略该行的其余部分,以便它可以再次尝试。

Demo