Infinite loop with cin when typing string while a number is expected

后端 未结 4 1930
长情又很酷
长情又很酷 2020-11-22 00:35

In the following loop, if we type characters as the cin input instead of numbers which are expected, then it goes into infinite loop. Could anyone please explai

4条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 01:20

    Perhaps, it's because,

    1. cin is a streaming function. When a non-numeric is entered instead of numbers, it is ignored. And you are prompted for re-entry.
    2. Even if you did give numeric inputs, you will be prompted for more inputs since you're on an infinite loop.

    You can solve this problem like this: 1. Create a function to take in a string input. 2. return it as numeric after conversion. Use strtod() for conversion.

    Hope this helps :)

提交回复
热议问题