Home > Enterprise >  while loop running for every digit/character from input
while loop running for every digit/character from input

Time:01-03

Hey guys beginner in C and coding in general. I am currently making a tictactoe program. For the part of the program I am validating user input. Since it is a 3x3 table, I want to make sure their input is an integer and that they choose a number between 1~9.

To do this I wrote

//Validating user input
void move() {
  std::cout << "It's Player" << player << "'s turn!\n";

  while(!(std::cin >> position)){
    std::cout << "Please choose a NUMBER between 1~9!\n";
    std::cin.clear();
    std::cin.ignore();
  }

  while(position < 1 || position > 9){
    std::cout << "Please choose a number BETWEEN 1~9!\n";
    std::cin.clear();
    std::cin.ignore();
  }
  
  while(board[position - 1] != " ") {
    std::cout << "Already filled please choose another number between 1~9!\n";
    std::cin >> position;
  }
}

It works but for some reason when I put in an input like 10, it would print Please choose a number BETWEEN 1~9! twice (for each digit) and if I input in for example "apple" it would print Please choose a NUMBER between 1~9! four times (for each character). How do i make it just print out the statement once?

Thank you!

CodePudding user response:

while(position < 1 || position > 9){

This while loop will continue running as long as position is less than 1 or greater than 9, that's what this says.

But there's nothing in the while loop itself that changes the value of position. For that simple reason, if position's value at this point is outside of the range of 1-9, this while loop will execute forever.

You always need to keep in mind The Golden Rule Of Computer Programming: your computer always does exactly what you tell it to do instead of what you want it to do. Here, you told your computer to execute this while loop as long as position is less than 1 or greater than 9, so this is what your computer will do until this is no longer the case.

CodePudding user response:

You can change your code as this. With this you run your while loop ones for every input. Until you get the value as you like. If the value is as you wish, you get out of the loop with break

std::cout << "Please choose a NUMBER between 1~9!\n";
  while(std::cin >> position){
    std::cin.clear();
    std::cin.ignore();

    if(position < 1 || position > 9){
        std::cout << "Please choose a number BETWEEN 1~9!\n";
    }else{
        break;
    }
  }
  •  Tags:  
  • c
  • Related