从类成员函数打印结构输入

时间:2013-03-11 04:14:19

标签: c++

我想知道如何输入/初始化start_dateend_date(来自Date month整数的结构day来自函数`initializeDate的year。一旦我能够初始化,我假设我将能够在打印输出成员函数中使用相同的逻辑。

struct Date
{
    int month;
    int day;
    int year;
};


void initializeDate(Date &d)
{
    cout<<"Please enter the month"<<endl;
    cin>>start.month;
    cout<<"Please enter the day"<<endl;
    cin>>start.day;
    cout<<"Please enter the year"<<endl;
    cin>>start.year;
    string dummy;
    getline(cin, dummy);
}

编辑:我得到的错误是'start'未在此范围内声明。

3 个答案:

答案 0 :(得分:1)

这是非常基础的,请阅读一本关于C ++的好书。发布在下面,因为你付出了努力:)

void Information::initializeDate(Date &d)    //comes from the Information class.
{
    // Commented as part of question change!  
    // Date d;     // Guessing that the structure is the private member of the class.
    cout<<"Please enter the month"<<endl;
    cin>>d.month;
    cout<<"Please enter the day"<<endl;
    cin>>d.day;
    cout<<"Please enter the year"<<endl;
    cin>>d.year;
    string dummy;
    getline(cin, dummy);
}

**只是根据您的问题更改编辑了代码

答案 1 :(得分:1)

看起来您不断更新示例代码。根据目前的修订版,我认为这就是你想要的:

#include <iostream>
using namespace std;

struct Date
{
    int month;
    int day;
    int year;
};


void initializeDate(Date &date)
{
    cout<<"Please enter the month"<<endl;
    cin>>date.month;
    cout<<"Please enter the day"<<endl;
    cin>>date.day;
    cout<<"Please enter the year"<<endl;
    cin>>date.year;
}

int main()
{
  Date start, end;
  initializeDate(start);
  initializeDate(end);
  cout << start.year << "/" << start.month << "/" << start.day << endl;
  cout << end.year << "/"   << end.month   << "/" << end.day << endl;
  return 0;
};

答案 2 :(得分:0)

好的,这里有几个问题,你应该瞄准。首先,为了修复代码,错误非常简单:代码中没有声明/定义名为start的变量的任何地方。所以,编译器会问你start是什么。我假设您正在尝试初始化您在函数initializeDate中传递的d成员的值,而您所要做的就是用{start替换每个出现的单词d {1}},你会得到:

void initializeDate(Date &d)
{
    cout<<"Please enter the month"<<endl;
    cin>> d.month;
    cout<<"Please enter the day"<<endl;
    cin>> d.day;
    cout<<"Please enter the year"<<endl;
    cin>> d.year;
    string dummy;
    getline(cin, dummy);
}

现在,虽然这有效,但它不是初始化日期的最佳方式。由于Datestruct,因此您可以使用构造函数方法初始化其成员。这可以通过这样编写来实现:

struct Date{
    int day, month, year;
    Date(int, int, int);
    };

Date:: Date(int day, int month, int year){
    this->day = day;
    this->month = month;
    this->year = year;
    }

int main(){
    Date today(11, 3, 2013);
    cout << "today, the date is " << today.day << "-" << today.month << "-" << today.year << endl; 
    return 0;
    }