我正在尝试制作一个具有菜单的程序,并且可以选择设置"当前"日期.我可以定义日期,它将一直保持到程序关闭.我有另一种方法来获取日期,通过询问用户链接一个人的日期,问题是它不会继续主菜单上的主要数据.它只是人员结构上.date的数据,我想我解释得很好.我尝试了很多方法,如果有人可以帮我解决的话,我真的无法理解...
typeData readData() { int val; typeData data; do { printf("Day: "); data.day = readInteger(MIN_DAYS, MAX_DAYS); printf("Month: "); data.month = readInteger(MIN_MONTH, MAX_MONTH); printf("Year: "); data.year = readInteger(MIN_YEAR, MAX_YEAR); val = validateData(data); if(val == 0) { printf("The data is not valid.\n"); } } while (val == 0); return data; }
我想我需要通过引用得到它,但我已经尝试了一段时间而且不能这样做.感谢大家.
虽然它是合法的C,但是按值传递结构并返回它们通常不是最好的方法.考虑:
void readData(typeData *data) { int val; do { printf("Day: "); data->day = readInteger(MIN_DAYS, MAX_DAYS); printf("Month: "); data->month = readInteger(MIN_MONTH, MAX_MONTH); printf("Year: "); data->year = readInteger(MIN_YEAR, MAX_YEAR); val = validateData(data); if (val == 0) { printf("The data is not valid.\n"); } } while (val == 0); }
更新:
以下是主程序示例以及示例更改validateData
:
int validateData(typeData *data) { int data_valid = 1; // check for error // this is whatever checks you already do ... if (data->... != ...) data_valid = 0; return data_valid; } int main(int argc,char **argv) { typeData main_data; readData(&main_data); // do something useful with the data [or transform it, etc] processData(&main_data); // print some results printData(&main_data); return 0; }
更新#2:
这是基于您最新示例的修改后的[部分]程序.我不得不猜测整个组织,但至少它有以下必要的变化menuPrincipal
:
int validateData(typeData *data) { int data_valid = 1; // check for error // this is whatever checks you already do ... if (data->... != ...) data_valid = 0; return data_valid; } char menuPrincipal(typeDate *date) { char option; if (date->day == 0 && date->month == 0 && data->year == 0) { printf("Date not set yet.\n"); } else { printf("Date: %d/%d/%d", date->day, date->month, date->year); } // more stuff return option; } int main(int argc,char **argv) { typeData main_data; char option; while (1) { readData(&main_data); option = menuPrincipal(&main_data); switch (option) { case 'a': // do something break; case 'b': // do something else break; default: printf("unknown option: '%c'\n",option); break; } } return 0; }
更新#3:
根据您的最新评论,我想我看到您遇到的问题.我已经使用了您最新的代码段并进行了更新:
// your original code -- this no longer works because readData is now void if (data->ano == 0 && data->mes == 0 && data->dia == 0) { Blah[*Bleh].date = readData(*data); } // one possibility -- but it does _not_ update "data" if (data->ano == 0 && data->mes == 0 && data->dia == 0) { readData(&Blah[*Bleh].date); } // this is more likely what you want -- it updates _both_: if (data->ano == 0 && data->mes == 0 && data->dia == 0) { readData(data); Blah[*Bleh].date = *data; }