![](/img/trans.png)
[英]C++ - I read a whole file (_which is a list of words separated by 2 white spaces_), how do i get the words separately fast?
[英]How do I read the whole number and fraction separately from input c++
我的疑問是從輸入流中跳過“ .
”並讀取兩個不同變量中的整數和小數部分。 假設我有一個類似10.26的輸入,我想將10
存儲在一個變量a
,將26
在另一個變量b
。
在C
,使用scanf
,我將像
scanf("%d.%d",&a,&b);
在使用cin
C++
等效的工作方式是什么? 還是應該包括cstdio
並使用scanf
本身?
您可以照常讀取浮點數,並使用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
}
讓operator>>
進行錯誤檢查!
您仍然可以在C ++中使用scanf
。 如果要使用cin
,則可以使用ignore
跳過.
在輸入中。 照常將整數讀入變量:
cin >> a;
cin.ignore(1, '.');
cin >> b;
請注意,無論使用什么,都會丟失有關小數部分的信息。 無論是.1
還是.001
,完成后都會發現b == 1
。 但是,它們的價值截然不同。
這是一種方法:
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'
請注意,這會(錯誤地?)將1.5E2
解析為1 + 0.5
,而不是150 + 0
。 您必須添加額外的邏輯來處理科學計數法情況。 讀取實際的float並使用modf
可能更簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.