2012-04-25 10 views
4

ユーザに入力を求めるときに "デフォルト値"を使用する方法を理解できません。ユーザーがEnterキーを押してデフォルト値を取得できるようにしたい。次のコードを考えてみましょう。ユーザ入力(cin) - デフォルト値

int number; 
cout << "Please give a number [default = 20]: "; 
cin >> number; 

if(???) { 
// The user hasn't given any input, he/she has just 
// pressed Enter 
number = 20; 

} 
while(!cin) { 

// Error handling goes here 
// ... 
} 
cout << "The number is: " << number << endl; 

答えて

9

std::cinからテキストの行を読み取るためにstd::getlineを使用してください。行が空の場合は、デフォルト値を使用します。それ以外の場合は、std::istringstreamを使用して、指定された文字列を数値に変換します。この変換に失敗すると、デフォルト値が使用されます。私はgetline()を使用して文字列として行を読み取るために誘惑されるだろうと、あなたは、変換プロセスを超える(間違いなく)もっとコントロールしまし

#include <iostream> 
#include <sstream> 
#include <string> 

using namespace std; 

int main() 
{ 
    std::cout << "Please give a number [default = 20]: "; 

    int number = 20; 
    std::string input; 
    std::getline(std::cin, input); 
    if (!input.empty()) { 
     std::istringstream stream(input); 
     stream >> number; 
    } 

    std::cout << number; 
} 
+0

は、ユーザーが有効な入力を入力しているかどうかを確認する方法があります(cinにあるように)。 私は、ユーザーが単に数字の代わりにいくつかの文字を入力し、エラーメッセージを投げるときを検出したいと考えています。 – tumchaaditya

0
if(!cin) 
    cout << "No number was given."; 
else 
    cout << "Number " << cin << " was given."; 
0

int number(20); 
string numStr; 
cout << "Please give a number [default = " << number << "]: "; 
getline(cin, numStr); 
number = (numStr.empty()) ? number : strtol(numStr.c_str(), NULL, 0); 
cout << number << endl; 

は、ここでサンプルプログラムです

7

これは、受け入れられた回答の代替として機能します。私はstd::getlineが過度の側面に少しあると言うでしょう。

#include <iostream> 

int main() { 
    int number = 0; 

    if (std::cin.peek() == '\n') { //check if next character is newline 
     number = 20; //and assign the default 
    } else if (!(std::cin >> number)) { //be sure to handle invalid input 
     std::cout << "Invalid input.\n"; 
     //error handling 
    } 

    std::cout << "Number: " << number << '\n';  
} 

ここには、3つの異なる実行と入力を持つlive sampleがあります。

+0

それは価値があるのですが、私は同意します - あなたのバージョンは私のものよりも好きです。 –

関連する問題