【问题标题】:how to check if the user CIN input are too little or too much?如何检查用户CIN输入是太少还是太多?
【发布时间】:2012-01-24 07:40:21
【问题描述】:

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

i 要求用户有 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 d\n", value);
    else
    {
        printf("%d is an even number d\n", 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 h\n", x);
    }

  }
  else
  {
      printf("Incorrect mode given ");

  }

  cin.get();
  _getch(); 
  return 0;

}

【问题讨论】:

  • 我不明白你的问题。你能举一个应该被接受/拒绝的输入的例子吗?另外,可以更具体地了解您的问题是什么?您的代码中是否有错误或其他错误?
  • 一个小提示:不要混用coutprintf!他们使用不同的缓冲系统,这些缓冲区将不匹配,因此输出可能看起来很奇怪。坚持一种方法(在 C++ 中推荐使用cout。)

标签: c++ visual-c++ logic


【解决方案1】:

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

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 是为了跳过用户在值之后写入的可能的垃圾数据。

您还应该验证用户是否为您提供了有效值,如果没有,则再次向用户询问这些值。

【讨论】:

    【解决方案2】:

    要记住的是,从控制台程序的角度来看,没有“用户”输入,只是输入。当有更多输入时程序不应该关心,当输入不足时程序不应该等待。输入是行缓冲的,因此用户必须按 Enter 才能传递输入,但“cin 如果这对您不起作用(因为该应用程序确实是面向用户的),那么您应该自己使用 getline() 和 separate 输入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      • 2020-09-03
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 2014-07-04
      相关资源
      最近更新 更多