C++ problem

  • C/++/#
  • Thread starter z-component
  • Start date
  • #1
479
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,182
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
479
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
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
479
2
I got it to work. Thanks everyone.
 

Related Threads on C++ problem

  • Last Post
Replies
3
Views
3K
  • Last Post
Replies
11
Views
2K
  • Last Post
Replies
4
Views
1K
  • Last Post
Replies
3
Views
2K
  • Last Post
Replies
3
Views
1K
  • Last Post
Replies
23
Views
5K
  • Last Post
Replies
6
Views
8K
  • Last Post
Replies
8
Views
6K
  • Last Post
Replies
15
Views
20K
  • Last Post
Replies
8
Views
3K
Top