What is weird with this c++ code?

Matt B

New member
include<iostream.h>

char roll;

int main()
{
cout<<"Yahtzee\n";
while (roll != 'Y' && roll != 'N')
{
cout<<"Roll? (Y/N)\n";
cin>>roll;
}
system("PAUSE");
}

It outputs:
Yahtzee
Roll? (Y/N)

If i type in anything that is longer than one character, "Roll? (Y/N)" will appear the same number of times as the length of what i entered in.
Why does this happen and is there a better way to go about this?
 
roll is a single character so when you do

cin >> roll;

the program reads in the next character. If you enter in multiple characters then it will pick up the next one right away.

for example, if you hit
12345 it will pick up 1, then 2, then 3, and so on. After the 5 it will prompt again and wait
 
Since it appears you want roll to be a character Use

cout << "Roll? (Y/N)\n" << endl;
cin.get(roll);


Use toupper or tolower to check for cases in input...
 
Back
Top