0

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

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

编辑:我得到的错误是“开始”没有在这个范围内声明。

4

3 回答 3

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

** 刚刚根据您有问题的更改编辑了代码

于 2013-03-11T04:19:13.893 回答
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;
};
于 2013-03-11T04:21:30.757 回答
0

Ok, there are a couple of problems here, that you should target. First, to fix your code, the error is very simple: there isn't anywhere in your code in which a variable named start was declared/defined. So, the compiler is asking you what start is. You are trying, I assume, to initialize the values of the members of d, that you passed in the function initializeDate, and all you have to do is just replace every occurence of the word start with d, and you'll get:

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

Now, although this works, it's not the best way to initialize the date. Since Date is a struct, you can initialize its members using a constructor method. This is achieved by writing it like this:

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;
    }
于 2013-03-11T04:39:50.363 回答