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;
}
This is the simple code for creating several objects based on input by the user. I have classes and methods set up. It works just fine without the do while loop. But I cant create the objects based on the users input and print them. The following line show error "has no member getname." and same error for every method called. I understand why this is happening but is there any solution to this?
name.getname().c_str(), name.getage(), name.getsound().c_str(), name.getowner().c_str());
Your code has some issues.
First: You declared two variables with the same name in different scopes: string name
in the main()
scope and Dog name
in the do ... while
scope. The Dog
object only exists inside the do ... while
loop. When you try to access it outside the loop, you get the error ... has no member getname
because you're actually accessing a string
object, not a Dog
object.
Second: You're not storing the Dog
s information that the user enters.
You need to use a vector to store the Dog
objects:
#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;
}