for (int i = 0; i < n; i++) { if (i % 2 == 0) { f << student[i].name << endl; f << student[i].GPU << endl; } if (i % 2 != 0) { f << student[n - i].name << endl; f << student[n - i].GPU << endl; } } - You should split the initial array of structures according to the even-odd criterion into partitions and write it to the file one by one. - Vlad from Moscow
2 answers
If I correctly understood your problem, then there are two approaches to its solution.
The first is to arrange the array, breaking it into two partitions, when at the beginning of the array will be located all the "even" elements, and then all the "odd" elements. And then you can simply write the elements of the resulting array in sequence.
To partition an array into partitions, you can use the standard std::partition or std::stable_partition declared in the <algorithm> header file.
The second approach is that you make two passes through the original array. First, from it write all the "even" elements, and then at the second pass in the cycle write all the "odd" elements.
- Thanks for the answer, but here it is necessary to do the following. I enter one entry at the end first, then enter the beginning of the file. And for some reason, with an even number of elements, he gives me 11, 44, 33, 22. That is, with an even number of input elements, he works out correctly - user6448834
- I just did this: I need to interleave the input to the file at the end-to-beginning. I just broke it because the zero element is better to combine with even elements of the array - user6448834
- @ user6448834 You cannot enter at the beginning, and then at the end of the file, and then again at the beginning. The file is written sequentially write by write to the end of the file. - Vlad from Moscow
- At first, I simply entered the values into the structure fields one by one. And then, when writing to the file, I write the first element of the structure, then the last, then the second, then the last one. I probably incorrectly described the task. The structure is filled with valid 11 (student's name) and a pair of 11 (average score) to it. The last student entered is 44 - 44. For some reason, this code works for me with an even number of students being entered - user6448834
Replace [ni] with [nin%2] , and everything will work out ...
Just look - making a few cycles with your hands - what do you get with even and with odd n ...