Using cin.get to get an integer

后端 未结 1 678
广开言路
广开言路 2020-12-20 12:13

I want to get a string of numbers one by one, so I\'m using a while loop with cin.get() as the function that gets my digits one by one.

But

相关标签:
1条回答
  • 2020-12-20 12:25

    cin.get can’t parse numbers. You could do it manually – but why bother re-implementing this function, since it already exists?*

    int number;
    std::cin >> number;
    

    In general, the stream operators (<< and >>) take care of formatted output and input, istream::get on the other hand extracts raw characters only.


    * Of course, if you have to re-implement this functionality, there’s nothing for it.

    To get the numeric value from a digit character, you can exploit that the character codes of the decimal digits 0–9 are consecutive. So the following function can covert them:

    int parse_digit(char digit) {
        return digit - '0';
    }
    
    0 讨论(0)
提交回复
热议问题