gpt4 book ai didi

C++传递值

转载 作者:行者123 更新时间:2023-11-30 05:33:47 24 4
gpt4 key购买 nike

代码

#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,然后像这样声明你的函数原型(prototype):

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

关于C++传递值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34574558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com