我使用struct和pointers编写了一个代码,问题是当你输入age时,结果将为0。如果你看看我的代码会很有帮助
Person's name: Billy
Person's age: 25
Write your hobby[0]:Kungfu
Write your hobby[1]:soccer
write your hobby[2]:basketball
Write your crush name: Jake
Name:Billy
Age:0
Hobbies[0]:Kungfu
Hobbies[1]:soccer
Hobbies[2]:basketball
Crush: Jake
由于某种原因,Age被分配到25但结果显示0为什么会发生
#include <iostream>
#include <string>
#include <Windows.h>
#include <sstream>
using namespace std;
//declare structure to store info about Billy
struct Son{
string name;
string crush;
int age;
string hobbies[3];
}Person;
int main(){
string sAge;
int i;
Son* info = new Son;
info = &Person;
//user interface
//Person's name
cout << "Person's name: ";
getline(cin, info ->name); //inputs person's name
//Person's age
cout << "Person's age: ";
//inputs person's age
getline(cin,sAge);
(stringstream)sAge << info ->age;
//for loop to get hobbies
for(i = 0; i < 3; i++){
cout << "Write your hobby[" << i <<"]: ";
getline(cin,info ->hobbies[i]); //inputs the person hobby three times
}
//Person's crush
cout << "Write your crush name: ";
getline(cin, info ->crush); //inputs the person's crush *opitional*
//output statement
cout << "Name: " << info ->name << endl; //display name
cout << "Age: " << info ->age << endl; //display age
for(int j = 0; j < 3; j++){ //display hobbies
cout << "Hobbies[" << j << "]: " << info ->hobbies[j] << endl;
}
cout << "Crush: " << info ->crush << endl; //display crush
delete info;
system("pause");
return 0;
}
答案 0 :(得分:3)
(stringstream)sAge << info ->age;
这不是正确的方法,您可以使用其中任何一个:
stringstream ss;
ss << sAge;
ss >> info->age;
info->age = atoi(sAge.c_str());
或者,您可以使用std::atoi(sAge)
立即接受std::string
,但是,由于您有using namespace std;
,因此应自动使用string
。感谢@alexolut说明这一点。
您基本上将stringstream
投射到stringstream
这是一个巨大的失败,string
不是static_cast
的子类。你也不应该在C ++中使用C风格的演员表,学会使用reinterpret_cast
,dynamic_cast
和Windows.h
来产生更好的警告(感谢@JohnZwinck说明这一点)。< / p>
附注:你包括{{1}}并且你没有使用它的任何功能。