注册 登录
编程论坛 C++教室

结构成员的读取问题

caochuan2000 发布于 2010-06-16 16:14, 586 次点击
帮忙看下我的程序哪有问题:
#include <iostream>
#include <string>
int main()
{
    using namespace std;
    struct car
    {
        string mader;
        int year;
    };
    car *ps=new car;
    int number;
    cout<<"How many cars do you wish to catalog:";
    cin>>number;
    for(int i=0;i<number;i++)
    {
        cout<<"\nCar #"<<i<<":"<<endl;
        cout<<"Please enter the make:";
        cin.get(*(ps+i).mader);
        cout<<"please enter the year made:";
        cin>>*(ps+i).year;
    }
    cout<<"Here is your collection:"<<endl;
    for(int i=0;i<number;i++)
        cout<<*(p+i).year cout<< *(p+i).mader<<endl;
}

编译出现:
error C2228: left of '.mader' must have class/struct/union type
error C2228: left of '.year' must have class/struct/union type
9 回复
#2
caochuan20002010-06-16 18:13
有知道的请帮忙看看,谢谢了啊
#3
debroa7232010-06-16 21:41
car *ps=new car;
这里有点错误,你的目的是想建立一个有number个元素的car数组,而这句代码只能为你建立一个car指针对象,那么在后面的
(ps+i)必然是个空想。
正确应该:
car *ps=null;

cin>>number;
后分配数组元素空间:;
ps = new car[number];
而且第二个for中的p,实在没搞明白是从什么地方变出来的。
#4
caochuan20002010-06-17 08:33
我改了还是编译不了啊,后面的P,写错了,是PS
#5
caochuan20002010-06-17 08:33
改动后的程序:
#include <iostream>
#include <string>
int main()
{
    using namespace std;
    struct car
    {
        string mader;
        int year;
    };
    int number;
    cout<<"How many cars do you wish to catalog:";
    cin>>number;
    car *ps=new car[number];
    for(int i=0;i<number;i++)
    {
        cout<<"\nCar #"<<i<<":"<<endl;
        cout<<"Please enter the make:";
        cin.get(*(ps+i).mader);
        cout<<"please enter the year made:";
        cin>>*(ps+i).year;
    }
    cout<<"Here is your collection:"<<endl;
    for(int i=0;i<number;i++)
        cout<<*(ps+i).year cout<< *(ps+i).mader<<endl;
}
#6
gaoce2272010-06-17 08:52
“ cout<<*(ps+i).year cout<< *(ps+i).mader<<endl;”
#7
caochuan20002010-06-17 09:56
6楼的什么意思啊?这句有错吗?
#8
南国利剑2010-06-17 13:35
以下是引用debroa723在2010-6-16 21:41:34的发言:

car *ps=new car;
这里有点错误,你的目的是想建立一个有number个元素的car数组,而这句代码只能为你建立一个car指针对象,那么在后面的
(ps+i)必然是个空想。
正确应该:
car *ps=null;

cin>>number;
后分配数组元素空间:;
ps = new car[number];
而且第二个for中的p,实在没搞明白是从什么地方变出来的。
严重同意以上看法。
#9
rainbow12010-06-17 19:01
此程序即按上面所说便改动编译也通不过。

[ 本帖最后由 rainbow1 于 2010-6-17 20:48 编辑 ]
#10
myth_feng2010-09-28 16:38
#include <iostream>
#include <string>
int main()
{
    using namespace std;
    struct car
    {
        string mader;
        int year;
    };
    int number;
    cout<<"How many cars do you wish to catalog:";
    cin>>number;
    car *ps=new car[number];
    for(int i=0;i<number;i++)
    {
        cout<<"\nCar #"<<i<<":"<<endl;
        cout<<"Please enter the make:";
        cin>>(ps+i)->mader;
        cout<<"please enter the year made:";
        cin>>(ps+i)->year;
    }
    cout<<"Here is your collection:"<<endl;
    for(int i=0;i<number;i++)
     {
      cout<<(ps+i)->year<<"  "<<(ps+i)->mader<<endl;

     }
     system("Pause");
}
1