使用cin.get获取一个整数 [英] Using cin.get to get an integer
问题描述
我想要一个一个数字字符串,所以我使用而
循环
与 cin.get ()
作为获取我的数字的函数。
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.
但 cin.get c $ c>得到的数字为
char
s,即使我试图使用
铸造我不能得到我的变量包含numrical值和而不是作为输入的数字的ascii值
。
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.
推荐答案
get
无法解析数字。您可以手动执行 - 但是为什么要重新实现此函数,因为它已经存在? *
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;
一般来说,流运算符(<<
和>>
)处理格式化的输出和输入, istream :: get $
In general, the stream operators (<<
and >>
) take care of formatted output and input, istream::get
on the other hand extracts raw characters only.
* 当然,
若要从数字字符获取数字值,您可以利用此功能来重新实现此功能。小数位0-9的字符代码是连续的。因此,以下函数可以隐藏它们:
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';
}
这篇关于使用cin.get获取一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!