-1

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.

Username
  • 3,463
  • 11
  • 68
  • 111

1 Answers1

1

You can't convert a string to an int that way. myString is of type char[], which the cast decays to char*, which is then converted to an int.

The standard library contains some methods that can convert from string to int.

Example: std::atoi

lcs
  • 4,227
  • 17
  • 36