0

//a is an integer but if an alphabet is press on run time the code keeps running without any input instead showing invalid output and repeat the loop turn again.

for (int j = 0; j <= 8; j++)
{
    if (j % 2 == 0){
        boad(arr);
        cout << "Player 1's turn " << endl << "Enter your position :";
        cin >> a;
        if (a == 0 || a == 1 || a == 2 || a == 3 || a == 4 || a == 5 || a == 6 || a == 7 || a == 8)
        {
            arr[a] = 'O';
            check(arr);
        }
        else 
        {

            cout << "invalid output";
            j = j - 1;
        }
    }
}
Felix
  • 2,548
  • 19
  • 48
  • Not really a solution, but might want to change that if to something like `if(0 <= a && a < 9)` – Felix Feb 25 '18 at 08:02
  • That's because when you press alphabet, its corresponding ASCII code sits in the variable 'a' , (a-z => 65-90, A-Z => 97-122), thus skipping the if block. – Jeffin Manuel Feb 25 '18 at 08:12
  • 1
    @JeffinManuel He's asking, why the else block is not running when given invalid output. – Felix Feb 25 '18 at 08:15
  • I am not sure what you are actually asking, though I think Felix has a good guess. Please show your output, explain what you do not like about it and maybe show the desired output. – Yunnosch Feb 25 '18 at 08:29
  • @Yunnosch when i press an alphabet it complete it's loop without asking for input and close. – Shaheer Ghouri Feb 25 '18 at 14:34

1 Answers1

1

The input stream keeps trying to read any number, and if fails, it sets the ios::failbit bit (which is a flag, that indicates that your read failed). So you could check cin.fail(), this checks the failbit,

    if (cin.fail()) {
        cout << "Invalid input\n";
    } else {
        cout << a << "\n";
    }

If you do this, when you type in a character, it will KEEP writing Invalid input, because it still tries to read a number, and you have a letter.

So, to make the stream read the line, then you extract a number from it, use std::getline, std::string, std::stringstream. Like that:

for(int i = 0; i < 4; i++) {
    std::string str;  // Create a string variable
    std::getline(cin, str); // Read a line, regardless of its components
    std::stringstream s(str); // Create a stream from this line
    s >> a; // Try to read an integer from this stream (which expresses the line)
    if (s.fail()) {
        std::cout << "Invalid input\n";
    } else {
        std::cout << a << "\n";
    }
}
user9335240
  • 1,739
  • 1
  • 7
  • 14