2016-01-13 22 views
-1

我幾天前開始學習C++。C++錯誤:從'char *'轉換爲'int'失去精度

我想使用用戶輸入設置dog.age

#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; 
} 

但我得到這個錯誤:即使我刪除(int)

error: cast from ‘char*’ to ‘int’ loses precision [-fpermissive] 
    age = (int)myString;` 

,它失敗。

爲什麼我的程序不能將myString作爲int

可選:如果我在構建類時做了其他問題,請隨時告訴我。我想盡早踢壞壞習慣。

+2

您不能從使用簡單的鑄件字符串轉換爲數字。 –

+0

@πάνταῥεῖ我還需要採取哪些其他步驟? – Username

回答

1

你不能以這種方式將字符串轉換爲int。 myString的類型爲char[],其中演員衰減到char*,然後轉換爲int

標準庫包含一些可以從字符串轉換爲int的方法。

例子:std::atoi

相關問題