C++ problem

  • C/C++
  • Thread starter z-component
  • Start date
  • #1
z-component
489
2
[SOLVED] C++ problem

I'm trying to make a structure of 4 elements to store an array of items. I'm trying to sort the lastName element in alphabetical, ascending order, but I keep getting errors around the last for loop. Can someone tell me what I'm doing wrong?


Code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

struct student {
	string firstName;
	string lastName;
	double GPA;
	int studentID;
};

int main()
{
	student s[10];

	ifstream in("people.txt");
	int numStudents = 0;

	const int size = 7;

	bool flag = true;
	for (int endIndex = size - 1; endIndex > 1 && flag; endIndex--) {
		flag = false;
		for (int startIndex = 0; startIndex < endIndex; startIndex++) {
			if (s[startIndex + 1].lastName < s[startIndex].lastName) {
				// adjacent elements in the array are out of order - swap them
				string temp = s[startIndex];
				s[startIndex] = s[startIndex + 1];
				s[startIndex + 1] = temp;
				flag = true; // set flag to show we have to continue...
				
			}
	}
	return 0;
}
 

Answers and Replies

  • #2
verty
Homework Helper
2,185
198
You keep getting errors? Does that mean you have run the algorithm and it doesn't sort the list correctly, or does it mean that it doesn't run?

I can see an extremely elementary error, any good IDE would show it.
 
  • #3
z-component
489
2
The program doesn't run at all. What is the error you found? Sometimes I got it to stop erring but then whenever I tried outputting I got more errors.
 
  • #4
Your.Master
34
0
Code:
[b][u]student[/u][/b] s[10];

[...]

[b][u]string[/u][/b] temp = s[startIndex];
s[startIndex] = s[startIndex + 1];
s[startIndex + 1] = temp;
}

Can you do this? Do you want to?
 
Last edited:
  • #5
z-component
489
2
I got it to work. Thanks everyone.
 

Suggested for: C++ problem

  • Last Post
Replies
30
Views
1K
Replies
1
Views
542
Replies
1
Views
421
  • Last Post
Replies
5
Views
659
  • Last Post
Replies
8
Views
751
Replies
14
Views
624
Replies
2
Views
527
Replies
34
Views
762
  • Last Post
Replies
14
Views
1K
  • Last Post
Replies
25
Views
955
Top