basically I'm trying to sort an array of strings using a bubble sort but when I run the program I get a message saying "main.exe has stopped working". I've tried this same program to sort integers instead of strings and everything works just fine. what do I need to do to make this work with strings?
int main()
{
int class_size;
int i,j;
cout <<"--------------------------------------"<<endl;
cout <<"Enter number of students. ";
cin >>class_size;
cout <<"--------------------------------------"<<endl;
string sort_array[class_size];
if(class_size<1 || class_size>25)
{
cout <<"Please enter value between 1 and 25."<<endl;
}
else
{
for(i=1; i<=class_size; i++)
{
cout <<"Enter student name number "<<i<<": ";
cin >>sort_array[i];
cout <<"--------------------------------------"<<endl;
}
That's what I was thinking but I had tried comparing strings with the "<" operator and everything worked fine it wasn't until I tried comparing string arrays in the same manner that I had problems.
#include <string>
#include <iostream>
int main()
{
using std::string;
string a("eggs");
string b("toast");
if (a<b) std::cout << "b is greater than a" << std::endl;
if (b>a) std::cout << "a is less than b" << std::endl;
}
Back to the OP, the problem is that you've screwed up the value of i. When you make an array of size i, the elements are numbers from zero to (i-1).
Here for(i=1; i<=class_size; i++)
you start at element 1 and you finish at element class_size, which does not exist, so you're reading memory that isn't yours. This is bad. Luckily for you, a segFault is thrown. You made this mistake twice, and a similar mistake with j.
This takes less than thirty seconds to find using a debugger. Learn to use one. It will save you so much time.
I don't understand if I can compare strings like integers then why doesn't it work with arrays?
here's a little program i made to test it and I get the same message "main.exe has stopped working".
#include <iostream>
#include <string>
using namespace std;
When you make an array of size i, the elements are numbered from zero to i-1. I could have sworn I told you that already. Maybe I wasn't clear enough. I'll try again.
See this? string array[2];
This creates an array of string, named array.
Here is the first string: array[0];
Here is the second string: array[1];
How many strings were there? Two. Is there a third string? No, there is not. So does array[2] exist? No.