while loop to infinity when the input of a cin is a 'dot'

后端 未结 4 2019
执念已碎
执念已碎 2021-01-27 19:22

I am having trouble using the cin method to acquire a variable. When the input is a number there is no problem, but when it is a special character like a dot [.], the whileloop

4条回答
  •  星月不相逢
    2021-01-27 19:59

    Make race an char, then you will be able do to:

    while (*race < '1' || *race > '3')
    

    which is probably what you want to achieve.

    Explanation:

    When you cin >> into an int, it converts given ASCII string to integer value. . doesn't have an integer meaning, so it isn't read into race and failbit is set - further >>s are no-op, until you clear them. However, if you cin >> into char and compare it with other chars (well, their ASCII codes, actually), you will be able to check it without troubles.

提交回复
热议问题