简体   繁体   中英

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

this might be an easy question, just for my own info only.

i requires the user to have 2 input.

how does the C++ console know that the user are short of 1 input when the user pressed enter/return key or when the user had enter more then 3 input ?

thanks for the answer.

#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;

}

Instead of letting the user input two values on one line, prompt the user for each input.

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');

This will make sure the user know he has to input two values, and you know you will have two values. The call to ignore is to skip possible junk data the user writes after the value.

You should also verify that the user gave you valid values, and if not then ask the user for the values again.

The thing to remember is that from a console program point of view, there is no "user" input, just input. The program shouldn't care when there is more input and wait when there is not enough. Input is line-buffered so the user has to press enter to pass input, but "cin <<" separates input based on whitespace.
If this doesn't work for you (because the application is really user oriented), then you should use getline() and separate the input yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM