2017-11-02 48 views
-1

ユーザーはダブルを入力する必要がありますが、文字列や文字を無視するようにプログラムを設定する方法はありますか?現在のコードで問題となるのは、プログラムがスパムになり、 cout < <「長方形の長さは何ですか?ユーザーが入力した文字列を無視するにはどうすればよいですか?

double length; 

do { 
    cout << "What is the length of the rectangle: "; 
    cin >> length; 
    bString = cin.fail(); 
} while (bString == true); 
+1

'while(bString == false);' Btw、あなたはあなたのコードに何が問題なのか言っていませんでした。 – DimChtz

+0

@DimChtz私が使うとき(bstring == false); –

+0

'std :: cin :: fail()'は、 'cin'への最後の呼び出しが失敗した場合に' true'を返します。だから、 'cin'が失敗しない限りループしたいので、' while(bString == false); 'が必要です。 – DimChtz

答えて

1
do { 
    cout << "What is the length of the rectangle: "; 
    cin >> length; 
    bString = cin.fail(); 
    cin.clear(); 
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); 
} while (bString == true); 

これは私の問題で動作するコードです。

-1

ユーザーが無効なデータ型を入力した場合、cinは失敗します。あなたは、整数と浮動小数点数を区別しません。この

double length; 
while(true) 
{ 
    std::cout << "What is the length of the rectangle: "; 
    std::cin >> length; 

    if (std::cin.fail()) 
    { 
     std::cout << "Invalid data type...\n"; 
     std::cin.clear(); 
     std::cin.ignore(); 
    } 
    else 
    { 
     break; 
    } 
} 
+2

「NULL」は使用しないでください。どうしてですか? – DimChtz

+0

@DimChtz、あなた、私のソリューションを更新しました。 –

+0

あなたの解決策は間違っています。見てください。 – DimChtz

0

cin.fail()を使用して確認することができます。

チェックする最も良い方法は、std::fmod()機能を使用して、リマインダーがゼロ以上かどうかを確認することです。それが浮動小数点数ならば、

ここコード

#include <cmath> 

int main() 
{ 
    double length; 
    std::cout <<"What is the length of the rectangle: "; 
    std::cin >> length; 

    if (std::cin.fail()) 
    { 
     std::cout<<"Wrong Input..."<<std::endl; 
    } else 
    { 
     double reminder = fmod(length, 1.0); 
     if(reminder > 0) 
      std::cout<<"Yes its a number with decimals"<<std::endl; 
     else 
      std::cout<<"Its NOT a decimal number"<<std::endl; 
    } 
} 

このコードが12及び12.0を区別しないことに注意してくださいです。

関連する問題