Using cin.get to get an integer

我的梦境 提交于 2019-12-29 08:27:10

问题


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 cin.get() gets the digits as chars and even though I'm trying to use casting I can't get my variables to contain the numrical value and not the ascii value of the numbers I get as an input.


回答1:


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';
}


来源:https://stackoverflow.com/questions/13421965/using-cin-get-to-get-an-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!