The task:
Create a program "List of students of the group", in which are specified - Last name, first name, gender, place of birth, year of birth. Need to generate files:

  1. The list of boys born in the city whose name is entered from the keyboard
  2. List of girls
  3. List of students born in the year that is entered from the keyboard. files to organize.

My question is this- How do I make the simultaneous use of two conditions with an object.
That is, using the function, finding only boys and the desired city. Here is the code itself, the functions with the object are all there (they are commented out)


#include <iostream> #include <string> using namespace std; struct Student //Структура Студент { char Family[35]; //Фамилия студента char Name[35]; //Имя студента char Sex[20]; //Пол студента char City[100]; //Город рождения студента int Date[3]; //Дата рождения студента void Show(); //Функция будет отображать данные студента void Input(); //Функция ввода данных в структуру void Gorod();// Город void Year(const int Date1, const int Date2);//год }; void Student::Input() { cout << "\n\n"; cout << "Family\t\t"; cin.getline(Family, 35); //Считали фамилию cout << "Name \t\t"; cin.getline(Name, 35); //Считали имя int k; cout << "Sex chouse 1=Male ,2 =Female \t\t";//Выбираем пол cin >> k; if (k == 1) strcpy(Sex, "Male"); else strcpy(Sex, "Female"); cout << "Date born\t"; cin >> Date[0]; //cin.ignore(); cin >> Date[1]; //cin.ignore(); cin >> Date[2]; cin.ignore(); cout << "City\t\t"; cin.getline(City, 100); cout << "\n\n"; cout << "======================\n"; } void Student::Show() //Функция показывает данные структуры на экране { cout << Name << " " << Family << "\n" << "Sex: " << Sex << "\nBorn in " << Date[0] << "." << Date[1] << "." << Date[2] << "\n"; cout << "In the city which is called " << City << "\n\n"; } void Student::Gorod() { char s1[20]; cout << "\nВедите нужный город:"; gets(s1); if (strcmp(s1, City) == 0) { cout << "\nГорода одинаковые записываем в файл" << endl; } else { cout << "\nГорода разные не записываем в файл" << endl; } } void Student::Year(const int Date1, const int Date2) //Внутри функции ничего менять не планируется, поэтому константы { if ((Date[2]>Date1) && (Date[2]<Date2)) Show(); //Проверка принадлежности диапазону и при вхождении в диапазон вывод элемента структуры на экран }; int prompt_menu_item() { // Выбранный вариант меню int variant; cout << "Choose you variant\n" << endl; cout << "1. Men born in towns\n" //список юношей родившихся в городе, вводим с клавы << "2. Only girls\n" //только девушки << "3. All students born in years\n" //список всех студентов родившихся в годах с какого то по какой то, вводим с клавы << "4. Open file\n" << endl; cout << ">>> "; cin >> variant; return variant; } int main() { ////////ЭТО НУЖНЫЕ ФУНКЦИИ// //for (int i = 0; i < N; i++) Student[i].Show(); //С помощью цикла показываем заполненную структуру на экране, вызывая метод структуры. //for (int i = 0; i < N; i++) Student[i].Gorod();// C помощью цикла показываем нужные города //for (int i = 0; i < N; i++) // if (strcmp(Student[i].Sex, "Male") == 0) // Student[i].Show(); //С помощью цикла показываем всех мальчиков. //for (int i = 0; i < N; i++) // if (strcmp(Student[i].Sex, "Female") == 0) // Student[i].Show(); //С помощью цикла показываем всех девочек. /////////////////// const int N = 2; //Количество элементов в структуре Student Student[N]; //Структура студентов из N элементов. (Справа объект, слева тип) for (int i = 0; i < N; i++) Student[i].Input(); //С помощью цикла заполняем структуру, вызывая метод структуры. setlocale(LC_ALL, "Rus"); int variant = prompt_menu_item(); switch (variant) { case 1: for (int i = 0; i < N; i++) if (strcmp(Student[i].Sex, "Male") == 0) Student[i].Show()&& for (int i = 0; i < N; i++) Student[i].Gorod(); system("pause"); break; int o, p; cout << "Enter need yaers\t"; cin >> o; cin >> p; // ввод нужных годов for (int i = 0; i < N; i++) Student[i].Year(o, p); //Выводим студентов, которые родились в нужные года cin.get(); system("pause"); } } 
  • Damn, I did not understand how to insert the code normally. - papalimer
  • 3
    The two conditions are combined into one condition with the help of the logical AND operator (AND), which is denoted as &&. - Vlad from Moscow
  • @VladfromMoscow Here I am making a mistake. case 1: for (int i = 0; i <N; i ++) if (strcmp (Student [i] .Sex, "Male") == 0 && Student [i] .Gorod) Student [i] .Show; system ("pause"); break; - papalimer
  • @BalinMisha Remove all unnecessary code, leave only what rushes to the question and format (there are 4 leading indents necessary for the backlight to turn ) - Cerbo
  • @VladfromMoscow I kind of put it in, but I don’t need it to work - papalimer

2 answers 2

Here are examples of how to combine several conditions into one, alter them for yourself.

 struct Car { enum Types { SEDAN , HATCHBACK , UNIVERSAL , COUPE }; Types Type; char Model[16]; int Speed; }; #define CARS_COUNT (128) Car cars[CARS_COUNT]; // считаем что массив с машинами как-то заполнен // 1. выводим модели всех седанов со скоростью большей или равной 120 и меньшей 160 for(int i = 0; i < CARS_COUNT; ++i) // для каждой машины из массива { if( Car::SEDAN == cars[i].Type // тип равен седан && 120 <= cars[i].Speed // и скорость больше или равно 120 && 160 > cars[i].Speed ) // и скорость меньше 160 { // если все логическое выражение в if вычисляется в true // попадаем в этот блок и выводим модель std::cout << cars[i].Model << "\n"; } } // 2. подсчитываем количество хатчбеков и купе со скоростью 150 int count = 0; for(int i = 0; i < CARS_COUNT; ++i) { if( ( Car::HATCHBACK == cars[i].Type // тип равен хетчбек || Car::COUPE == cars[i].Type ) // или тип равен купе && 150 == cars[i].Speed ) // и скорость равна 150 { ++count; } } std::count << "\ncount = " << count << "\n"; 

    I'm certainly not a C programmer, but

      for (int i = 0; i < N; i++) { if (strcmp(Student[i].Sex, "Male") == 0) Student[i].Show(); //С помощью цикла показываем всех мальчиков. } for (int i = 0; i < N; i++) { if (strcmp(Student[i].Sex, "Female") == 0) Student[i].Show(); //С помощью цикла показываем всех девочек. } 

    it seems to me that students can be either a boy or a girl. Well, okay, you have a problem most likely in the syntax where it is not where there is a bracket ( ) or { } since you do not comply with any coding style, then I think you all are better if for and so on. Operators lead to the mind if() { } , etc. then it will be something visible. You said what kind of error?

    and how to understand the code below

      case 1: for (int i = 0; i < N; i++) if (strcmp(Student[i].Sex, "Male") == 0) Student[i].Show()&& for (int i = 0; i < N; i++) Student[i].Gorod(); system("pause"); break; 

    we go in case 1 we perform for then in if and so that we don’t put normal brackets show the student and then we execute the city in for ?