如何检查用户CIN输入是太少还是太多

how to check if the user CIN input are too little or too much?

本文关键字:输入 太多 CIN 用户 何检查 检查      更新时间:2023-10-16

这可能是一个简单的问题,仅供我自己参考。

我要求用户有2个输入。

当用户按下回车键或用户输入了超过3个输入时,C++控制台如何知道用户缺少1个输入?

谢谢你的回答。

#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h> 
using namespace std; 
int main() 
{ 
   char hord;
   int x;
   char userInput[256] ;
   int value;
  cout<<"Please enter a ./Even mode number: "; 
  cin >> hord >> userInput;
  if(hord == 'd')
  {
    value = atoi(userInput);
    cout <<"Selected Base 10" << endl;
    if (value % 2) /*or *///(x & 1)
    printf("%d is an odd number dn", value);
    else
    {
        printf("%d is an even number dn", value);
    }
  }
  else if(hord =='h')
  {
   sscanf_s(userInput, "%x", &x);
    if (x % 2)
    {/*or *///(x & 1)
    printf("%d is an odd number h n", x);
    }
    else
    {
        printf("%d is an even number hn", x);
    }
  }
  else
  {
      printf("Incorrect mode given ");
  }
  cin.get();
  _getch(); 
  return 0;
}

不要让用户在一行上输入两个值,而是提示用户输入每个值。

std::cout << "Enter the first value and press ENTER: ";
std::cin >> value1;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
std::cout << "Enter second value and press ENTER: ";
std::cin >> value2;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');

这将确保用户知道他必须输入两个值,并且您知道您将有两个值。对ignore的调用是跳过用户在值之后写入的可能的垃圾数据。

您还应该验证用户是否给了您有效的值,如果没有,请再次向用户询问值。

需要记住的是,从控制台程序的角度来看,没有"用户"输入,只有输入。程序不应该关心何时有更多的输入,而应该等待何时没有足够的输入。输入是行缓冲的,因此用户必须按enter键才能传递输入,但"cin<<"会根据空白分隔输入
如果这对您不起作用(因为应用程序实际上是面向用户的),那么您应该使用getline()并自己分离输入。