2016-10-13 26 views
-4

私は配列を持っている、私はユーザーにフルネームを入力するように頼みたい。 getlineのがエラーを示していますが、私はなぜ知らない、私は、ライブラリを定義している:定義されたライブラリにもかかわらず、C++でgetline()エラーが発生しましたか?

#include <iostream> 
#include <string> 
int main() 
{ 
    using namespace std; 
    const int ArSize = 20; 
    char name[ArSize]; 
    char dessert[ArSize]; 
    cout << "Enter your name:\n"; 

    getline(cin, name) ; 

    cout << "Enter your favorite dessert:\n"; 
    cin >> dessert; 
    cout << "I have some delicious " << dessert; 
    cout << " for you, " << name << ".\n"; 
    return 0; 
} 

enter image description here

+1

「Getline shows error」より具体的にお聞かせください。 – AndyG

+3

'name'と' dessert'は 'std :: string'sである必要があります。 – NathanOliver

+0

文字列の代わりに文字配列を使用しているのはなぜですか? – AndyG

答えて

1

グローバル関数getline 2番目のパラメータ、NOT NULL終端文字列(またはcharの配列としてstd::string&を期待します)。 http://en.cppreference.com/w/cpp/string/basic_string/getlineを参照してください。

メンバ関数std::istream::getlineは配列で動作することができますが、2番目のパラメータが必要です。 http://en.cppreference.com/w/cpp/io/basic_istream/getlineを参照してください。

次のいずれかを使用することができます:

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

または

char name[ArSize]; 
cin.getline(name, sizeof(name)); 
0

主な理由は次のとおりです。cin.getlineの差(のchar *、int型)とのgetline(CIN、文字列)を作ります。

cin.getline()フォーマットされていない入力としてストリームから文字を抽出し、c-stringとしてsに格納します。 getlineはistreamのメンバ関数です。 あなたのコードは次のようになります。

cin.getline(name, ArSize); 

のgetlineの他のバージョンを我々はそれを呼び出すためにメンバアクセス演算子 を使用しない理由、それは、このいずれかのcalssのメンバーではない文字列 を取る関数です。

string name; 
getline(cin, name); 
0

お試しcin.getline(name,ArSize);

関連する問題