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
Using cin.get to get an integer
提问by Quaker
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.
我想一个一个地得到一串数字,所以我使用了一个while
循环cin.get()
作为一个一个一个地得到我的数字的函数。
But cin.get()
gets the digits as char
s 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()
将数字作为char
s ,即使我尝试使用强制转换,我也无法让我的变量包含数值,而不是我作为输入获得的数字的 ascii 值。
回答by Konrad Rudolph
cin.get
can'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::get
on 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';
}