I started learning C++ a few days ago.
I want to set dog.age
using user input.
#include <iostream>
using namespace std;
class dog{
public:
dog();
~dog();
int getAge();
void setAge(int a);
protected:
int age;
};
dog::dog(){
}
dog::~dog(){
}
int dog::getAge(){
return age;
}
void dog::setAge(int a){
age = a;
}
int main(){
dog myDog;
char myString[2];
int age;
cout<<"How old is the dog? ";
cin.getline(myString,2,'\n');
age = (int)myString;
myDog.setAge(age);
cout<<"The dog is "<<myDog.getAge()<<" years old!\n";
return 0;
}
But I get this error:
error: cast from ‘char*’ to ‘int’ loses precision [-fpermissive]
age = (int)myString;`
Even if I remove (int)
, it fails.
Why won't my program cast myString
as an int
?
OPTIONAL: If I'm doing something else wrong with constructing classes, feel free to tell me. I'd like to kick bad habits early.