C++ 使用 cin.get 获取整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13421965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:17:08  来源:igfitidea点击:

Using cin.get to get an integer

c++casting

提问by Quaker

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

我想一个一个地得到一串数字,所以我使用了一个while循环cin.get()作为一个一个一个地得到我的数字的函数。

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.

但是cin.get()将数字作为chars ,即使我尝试使用强制转换,我也无法让我的变量包含数值,而不是我作为输入获得的数字的 ascii 值。

回答by Konrad Rudolph

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

cin.get无法解析数字。你可以手动完成——但为什么要重新实现这个函数,因为它已经存在了?*

int number;
std::cin >> number;

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

一般来说,流操作符(<<>>)负责格式化输出和输入,istream::get另一方面只提取原始字符。



*Of course, if you haveto 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:

要从数字字符中获取数值,可以利用十进制数字 0-9 的字符代码是连续的。所以下面的函数可以隐藏它们:

int parse_digit(char digit) {
    return digit - '0';
}