码
#include <iostream>
#include <string>
#include <fstream>
#include <stdio.h>
using namespace std;
void case1();
void case2();
struct Students
{
char first_name[10];
char last_name[10];
char country[20];
};
int n, i;
int main()
{
char selection;
do //MENU
{
cout << "\n\nMENU\n";
cout << "1. Case 1: \n";
cout << "2. Case 2: \n";
cout << "3. Exit";
cin >> selection;
switch (selection)
{
case '1': {
system("cls");
case1();
} break;
case '2': {
//system("cls");
case2();
} break;
}
} while (selection != '3');
return 0;
}
//*Function 1
void case1()
{
Students array[10];
int i;
cin >> n;
for (i = 0; i < n; i++)
{
cout << "Name:";
cin >> array[i].first_name;
cout << "Last Name:";
cin >> array[i].last_name;
cout << "Country:";
cin >> array[i].country;
}
for (i = 0; i < n; i++)
{
cout << array[i].first_name << " ";
cout << array[i].last_name << " ";
cout << array[i].country << endl;
}
}
//Function 2
void case2()
{
Students array[10];
char choose[2];
//* I must use n and Students array [10] that I enter for the keyboard in function 1
do {
cout << "New check? Y/N \n";
cin >> choose;
if (_stricmp("N", choose) == 0)
{
break;
}
char name_for_check[10];
cout << "\n Name for check:";
cin >> name_for_check;
for (i = 0; i < n; i++)
{
if (strcmp(array[i].first_name, name_for_check) == 0 || strcmp(array[i].country, name_for_check) == 0 || strcmp(array[i].last_name, name_for_check) == 0)
{
cout << array[i].first_name << " ";
cout << array[i].last_name << " ";
cout << array[i].country << endl;
}
}
} while (_stricmp("Y", choose) == 0);
}
我想要做的是在第一个函数和第二个函数中输入n
和数组,以使用我在第一个函数中输入的相同值。
还有别的。到目前为止,我已将结构用作全局结构。如何在main中定义我的结构并在case1()
和case2()
中使用它?
首先声明你的struct Students
之后声明你的函数原型:
struct Students
{
char first_name[10];
char last_name[10];
char country[20];
};
void case1( int &n, int maxN, Students array[] ); // int &n becaus n is output (reference to int)
void case1( int n, Students array[] ); // int n; because n is input
功能case1
看起来像这样
void case1( int &n, int maxN, Students array[] )
{
cin >> n;
if ( n <= 0 )
return;
if ( n > maxN )
n = maxN;
for (int i = 0; i < n; i++)
{
cout << "Name:";
cin >> array[i].first_name;
...
}
...
}
像这样称呼它:
int main()
{
....
Students array[10];
int n;
case1( n, 10, array );
case2( n, array );
...
我建议使用std::vector
而不是数组。另见你自己的问题Structures export data for specific name
#include <vector>
void case1( std::vector<Students> &array );
std::vector<Students> array;
case1( array );