[英]How do I read the whole number and fraction separately from input c++
My doubt is to skip a " .
" from the input stream and read the whole number and the fractional parts in two different variables. 我的疑问是从输入流中跳过“ .
”并读取两个不同变量中的整数和小数部分。 Say I have an input like 10.26, I want store 10
in one variable a
and 26
in another variable b
. 假设我有一个类似10.26的输入,我想将10
存储在一个变量a
,将26
在另一个变量b
。
In C
, using scanf
, I will do it like 在C
,使用scanf
,我将像
scanf("%d.%d",&a,&b);
What is the equivalent way to do in C++
using cin
? 在使用cin
C++
等效的工作方式是什么? or should I include cstdio
and use the scanf
itself? 还是应该包括cstdio
并使用scanf
本身?
You can read the float as normal and use C-library's modf
function to split the number: 您可以照常读取浮点数,并使用C库的modf
函数拆分数字:
#include <cmath>
float f = 0.0;
float ipart = 0.0;
float fpart = 0.0;
if (cin >> f)
fpart = modf(f, &ipart);
else {
// input failed
}
Let operator>>
do the error checking! 让operator>>
进行错误检查!
You can still use scanf
in C++. 您仍然可以在C ++中使用scanf
。 If you want to use cin
, then you can use ignore
to skip over the .
如果要使用cin
,则可以使用ignore
跳过.
in the input. 在输入中。 Read the integers into variables as usual: 照常将整数读入变量:
cin >> a;
cin.ignore(1, '.');
cin >> b;
Beware that whatever you use, you lose information about the fractional part. 请注意,无论使用什么,都会丢失有关小数部分的信息。 Whether the value is .1
or .001
, you'll find b == 1
when you're finished. 无论是.1
还是.001
,完成后都会发现b == 1
。 They're very different values, though. 但是,它们的价值截然不同。
Here's one way: 这是一种方法:
int egral;
unsigned int frac;
char sep;
if (!(std::cin >> egral >> sep >> frac) || sep != '.')
{
// error, could not parse number
}
// integral part is 'egral, fractional part in 'frac'
Note that this would (wrongly?) parse 1.5E2
as 1 + 0.5
, and not as 150 + 0
. 请注意,这会(错误地?)将1.5E2
解析为1 + 0.5
,而不是150 + 0
。 You'd have to add extra logic to handle scientific notation situations. 您必须添加额外的逻辑来处理科学计数法情况。 It might be simpler to read an actual float and use modf
. 读取实际的float并使用modf
可能更简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.