2017-03-02 7 views
0
int main() 
{ 
    string name, sound, owner; 
    int age; 
    int answer = 1; 
    int i = 0; 

    do 
    { 
     ++i; 
     puts("Enter the dog info below"); 
     puts("Dog's name: "); 
     cin >> name; 
     puts("Dog's sound: "); 
     cin >> sound; 
     puts("Dog's age: "); 
     cin >> age; 
     puts("Dog's owner: "); 
     cin >> owner; 

     puts("Do you want to add one more dogs to the database?\n1: Yes\n0:  No"); 
     cin >> answer; 

     Dog name(name, sound, age, owner); 

    } while (answer != 0); 

    for (int a = i; i > 0; i--) 
    { 
     printf("%s", name.getname().c_str()); 
     printf("\n\n%s is a dog who is %d years old, says %s and %s the owner\n\n", 
      name.getname().c_str(), name.getage(), name.getsound().c_str(), name.getowner().c_str()); 
    } 
    return 0; 
} 

これは、ユーザーの入力に基づいて複数のオブジェクトを作成するための単純なコードです。クラスとメソッドが設定されています。 whileループなしでうまく動作します。しかし、私はユーザーの入力に基づいてオブジェクトを作成して印刷することはできません。次の行は、 "has have member getname"というエラーを示しています。と呼ばれるすべてのメソッドで同じエラーが発生します。なぜこれが起こっているのか理解していますが、これに対する解決策はありますか?ユーザー入力に基づいて複数のオブジェクトを作成してアクセスする方法 - C++

name.getname().c_str(), name.getage(), name.getsound().c_str(), name.getowner().c_str()); 
+0

は私達にあなたの 'Dog'クラスを表示します。 – user1286901

+0

「なぜこれが起こっているのか理解しています」 - あなたの知識レベルを測るのに役立っている理由を説明してもらえますか? – immibis

答えて

1

コードにはいくつか問題があります。

まず:do ... while範囲でmain()範囲内string nameDog name:あなたは異なるスコープに同じ名前の2つの変数を宣言しました。 Dogオブジェクトは、do ... whileループ内にのみ存在します。ループ外でそのオブジェクトにアクセスしようとすると、Dogオブジェクトではなく、stringオブジェクトに実際にアクセスしているため、エラー... has no member getnameが発生します。

2番目:ユーザーが入力するDogの情報を保存していません。

あなたがDogオブジェクトを格納するためのベクターを使用する必要があります。

#include <vector> 

int main() 
{ 
    string name, sound, owner; 
    int age; 
    int answer = 1; 
    std::vector<Dog> dogs; // Vector to store Dog objects 

    do 
    { 
     puts("Enter the dog info below"); 
     puts("Dog's name: "); 
     cin >> name; 
     puts("Dog's sound: "); 
     cin >> sound; 
     puts("Dog's age: "); 
     cin >> age; 
     puts("Dog's owner: "); 
     cin >> owner; 

     puts("Do you want to add one more dogs to the database?\n1: Yes\n0:  No"); 
     cin >> answer; 

     Dog dog(name, sound, age, owner); 
     dogs.push_back(dog); // store current dog's info 

    } while (answer != 0); 

    for (int a = 0; a < dogs.size(); a++) 
    { 
     Dog& dog = dogs.at(a); // Get the dog at position i 

     printf("%s", dog.getname().c_str()); 
     printf("\n\n%s is a dog who is %d years old, says %s and %s the owner\n\n", 
      dog.getname().c_str(), dog.getage(), dog.getsound().c_str(), dog.getowner().c_str()); 
    } 
    return 0; 
} 
+0

ありがとうございました。 –

関連する問題