2013-03-24 89 views
0

我有以下簡單的代碼:如何使cin >>不將float轉換爲整數?

#include <iostream> 
int main() 
{ 
    int a; 
    std::cout << "enter integer a" << std::endl; 
    std::cin >> a ; 

    if (std::cin.fail()) 
    { 
     std::cin.clear(); 
     std::cout << "input is not integer, re-enter please" <<std::endl; 
     std::cin >>a; 
     std::cout << "a inside if is: " << a <<std::endl; 
    } 
    std::cout << "a is " << a <<std::endl; 
    std::cin.get(); 
    return 0; 
} 

當我運行上面的代碼和輸入:1.5,其輸出:a is 1。僅供參考:我使用gcc 4.5.3編譯並運行代碼。

這意味着如果cin需要一個整數但看到一個浮點數,它將隱式執行轉換。那麼這是否意味着cin看到一個浮點數時,它不是在fail()狀態?爲什麼會出現這種情況?是否因爲C++在>>運算符上進行了隱式轉換?

我也試過下面的代碼來決定一個給定的輸入數是否整數下面這個職位的想法:testing if given number is integer

#include <iostream> 
bool integer(float k) 
{ 
    if(k == (int) k) return true; 
    return false; 
} 

int main() 
{ 
    int a; 
    std::cout << "enter integer a"<< std::endl; 
    std::cin >> a ; 

    if (!integer(a)) 
    { 
    std::cout << "input is not integer, re-enter please" ; 
    std::cin.clear(); 
    std::cin >> a; 
    std::cout << "a inside if is: " << a <<std::endl; 
    } 
    std::cout << "a is " << a <<std::endl; 
    std::cin.get(); 
    return 0; 
} 

的代碼塊也無法測試是否a是因爲它的整數當我用float輸入運行時,只需跳過if塊。

那麼,爲什麼這是用cin獲取用戶輸入時的情況?如果有時我想輸入爲189,但偶然輸入了18.9,在這種情況下將導致18,這是不好的。那麼這是否意味着使用cin獲取用戶輸入整數不是一個好主意?

謝謝。

+0

line 4. int a; ---> double a; – enhzflep 2013-03-24 03:56:29

+1

如果你把輸入'a'作爲一個float而不是一個int,那麼檢查'a ==(int)a'是否會告訴你它是否是一個整數。 – Aiias 2013-03-24 03:57:36

+0

cin「知道」它讀取的是什麼類型,根據類型做不同的事情。對於int來說,它讀取數字,並在它看到非數字時立即停止。在你的例子中*不是*讀取整個「1.2」,它在「1」之後停止,因爲下一個字符不是數字。 – 2013-03-24 04:01:56

回答

6

當你讀取一個整數並給它一個1.5的輸入時,它看到的是整數1,並且它在該週期停止,因爲它不是整數的一部分。 「.5」仍然在輸入中。這就是你只能得到整數部分的原因,也是它似乎沒有等待第二次輸入的原因。

爲了解決這個問題,你可以讀取一個float而不是一個整數,這樣它就可以讀取整個值,或者可以在讀取整數後檢查線上是否還有其他東西。

1

閱讀用戶輸入時,我不喜歡使用operator>>,因爲用戶輸入通常基於行而且容易出錯。我覺得最好的一次讀取一行和驗證:

std::string line; 
std::getline(std::cin, line); 

這也可以很容易地檢查不同類型的數字。

std::stirngstream linestream(line); 
int val; 
char c; 

if ((linestream >> val) && !(linestream >> c)) 
{ 
    // Get in here if an integer was read. 
    // And there is no following (non white space) characters. 
    // i.e. If the user only types in an integer. 
    // 
    // If the user typed any other character after the integer (like .5) 
    // then this will fail. 
} 

當然提振已經支持這一點:

val = boost::lexical_cast<int>(linestream); // Will throw if linestream does 
              // not contain an integer or 
              // contains anything in addition 
              // to the integer. 

當然升壓轉換會花車爲好。

相關問題