infinite loop not letting me redefine variable

Hey! I've never posted on here and I am VERY new to c++, I don't know vocabulary and I'm extremely frustrated with what I'm currently dealing with, lol. So basically, the code I'm writing is suppose to have the user type a number between 1-7 and have it display that letter in "awesome", so I'm trying to do input validation.

I havent gotten around to the numbers part yet, but I'm using cin.fail() and every time I run it and put a letter instead of a number, it starts spamming "Invalid entry. Please try again.Enter a number from 1 to 7 and I will tell you which letter is at that position:" over and over.

So, I'm not sure if this is even the best way to go about what I'm trying to accomplish, my main question is just why does my input() function not let me input another number after the first one? Shouldn't it have me input another number in num once it gets back to cin >> num? Instead, it seems to skip over that and keeps the first number I put in before it looped back, and infinitely loops with that same input.

(again sorry for my terribly bad way of explaining, I am very new and have no clue how to talk about it yet, I'm learning)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  #include <iostream>
using namespace std;

const int size = 7;

int input();

int main()
{
  char word[size] = {'A', 'W', 'E', 'S', 'O', 'M', 'E'};
  cout << "I'm thinking of a 7 letter word.\n";

  int num = input();

  while(cin.fail())
  {
    cout << "Invalid entry. Please try again.";
    num = input();
  }  

  cout << "The letter in position " << num << " is " << word[num-1];

  return 0;
}

int input()
{
  int num;
  cout << "Enter a number from 1 to 7 and I will tell you which letter is at that position:";
  cin >> num;
  return num;
}
If you try to read an invalid input you will put the input stream in a failed state, so it will not be able to take any further input.

You need to clear the failed state (cin.clear()). It is probably a good idea also to remove anything else in the input buffer (cin.ignore(...) ). Thus:
1
2
3
4
5
6
7
  while(cin.fail())
  {
    cin.clear();
    cin.ignore( 1000, '\n' );   // 1000 should do unless you are sitting on the spacebar
    cout << "Invalid entry. Please try again.";
    num = input();
  }


You also need to test that your input number is >= 0 and < 7, but I leave that to you.
thank you so much! Yeah I got the rest of the code sorted as well, but that helped a lot :)
Topic archived. No new replies allowed.