为什么当我输入新的患者信息时,我的main中的计数没有更新?

  • 本文关键字:main 我的 更新 信息 患者 c++
  • 更新时间 :
  • 英文 :


为什么当我输入新的患者信息时,我的主count没有更新?我不知道为什么在我的add函数的case 2中,main中的count永远不会增加。即使在我输入新的患者信息之后,它仍然只有20(与我的输入文本相同)。
下面是我的代码:

struct PATIENT
{
string id;
string name;
string age;
string address;
string doc;
string diagnosis;
string status;
string date;
};
struct LIST
{
PATIENT patient[100];
};
void get_data(LIST* p, int* count);
void add(LIST* p, int* count);
int main()
{
LIST p;
int count, choice;
get_data(&p, &count);
cout << "The count is: " << count;
add(&p, &count);
}
void get_data(LIST* p, int* count)
{
int num = 0;
ifstream inFile;
inFile.open("input.txt");
if (!inFile)
{
cout << "Error to open an input filen";
exit(0);
}
else
{
while (num < 100 && !inFile.eof())
{
getline(inFile, p->patient[num].id);
getline(inFile, p->patient[num].name);
getline(inFile, p->patient[num].age);
getline(inFile, p->patient[num].address);
getline(inFile, p->patient[num].doc);
getline(inFile, p->patient[num].diagnosis);
getline(inFile, p->patient[num].status);
getline(inFile, p->patient[num].date);
num++;
}
}
*count = num;
inFile.close();
}
void add(LIST* p, int* count)
{
system("cls");
int patientSelect = 2;
switch (patientSelect)
{
case 1: cout << "Existing patient";
break;
case 2:system("cls");
cout << "ttttNew patient" << endl;
cout << "tttt===========" << endl;
cout << "Enter patient ID: ";
cin.ignore();
getline(cin, p->patient[*count].id);
cout << "Enter patient name: ";
getline(cin, p->patient[*count].name);
cout << "Enter age: ";
cin >> p->patient[*count].age;
cin.ignore();
cout << "Enter address: ";
getline(cin, p->patient[*count].address);
cout << "Enter attending doctor's name: ";
getline(cin, p->patient[*count].doc);
cout << "Enter diagnosis: ";
getline(cin, p->patient[*count].diagnosis);
cout << "Enter patient status: ";
getline(cin, p->patient[*count].status);
cout << "Enter consultation date: ";
getline(cin, p->patient[*count].date);
*count++;
system("PAUSE"); system("cls"); main();
break;
case 3: system("cls"); main();
default:cin.clear(); cin.ignore(numeric_limits<streamsize>::max(), 'n'); cout << "Invalid input, please try again..." << endl;
system("PAUSE"); system("cls");
}
}

我在main中的输出:计数为20(添加函数后)

这是c++操作符优先级。参见https://en.cppreference.com/w/cpp/language/operator_precedence

*count++修改为(*count)++。如果你不这样做,你的代码相当于*(count++),这是有效的c++,但它什么也不做…

但是我宁愿传递一个int引用给函数,而不是一个指向int的指针。这使得编码更简单,更不容易出错。

另一个问题是你从add内部再次调用main。但在main中,您从头开始:读取数据等。您的所有更改都将被覆盖。请考虑:

void setup(LIST& p, int& count) {
get_data(&p, &count);
}
void update(LIST& p, int& count) {
while (true) {
cout << "Command (0:exit, 2:add, etc.): "; 
int choice=0;
cin >> choice;
if (choice==0) {
break;
}  
cout << "The count is: " << count;
add(&p, &count);   /// <= I would also pass choice here as argument and use it instead of patientSelect, but please check your business logic. 
}
}
int main()
{
LIST p;
int count=0;
setup(p, count);
update(p, count);
}

当然,不要再从任何地方调用main。删除所有对main的调用

相关内容

最新更新