Struct/string function not working

Can anyone help me get this function working? It is supposed to reorder the words in alphabetical order. It only puts the first two words in order and ignores the rest. Thanks.

Here is Main:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{
    Word c[N];
    int i = 0;

    cout << "Enter the words: " << endl;
    for (; i < N; i++){
       c[i] = get();
       if (c[i].count == 0)
         break;
    if (isinorder(c,i)){
      cout << "Words are in order." << endl;
      put(c,i);
      }
    else{
      cout << "Words are not in order." << endl;
      put(c,i);
      sort(c,i);
      cout << "Words are now in order." << endl;
      put(c,i);
  }


This is how I am storing the numbers. I think it may not be right.

1
2
3
4
5
6
7
8
9
10
Word get()
{
   Word temp;

   if (cin >> temp.word)
     temp.count = 1;
   else
     temp.count = 0;
   return temp;
}



sort function:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
void sort(Word c[], int i)
{
int len = 0;
char temp[20];

if (strcmp(c[len].word, c[len+1].word) > 0){
  strncpy(temp, c[len].word, 19);
  temp[19] = '\0';
  strncpy(c[len].word, c[len+1].word, 19);
  c[len].word[19] = '\0';
  strncpy(c[len+1].word, temp, 19);
  c[len+1].word[19] = '\0';
  }
}


The isinorder function works fine so I didn't include it.
Last edited on
Uhhh.

1
2
3
4
5
6
typedef std::string Word;
int main()
{
  Word c[N];
  std::sort(c,c+N);
}
I'm not sure I follow you.
I'm saying that you're making a simple thing far too complicated.
In your sort function, you're apparently swapping Word objects. However, if you implement the copy constructor and operator= correctly for that class, none of that ridiculous code would be necessary and you could use std::swap.

Incidentally, std::string already provides that functionality and it can hold words or whatever you want it to - hence the typedef.

std::sort is part of the standard library and will sort a range of objects, provided operator< is implemented (again, std::string does this).
Oh, okay. We have just started talking about constructors and destructors (last 15 mins. of last class), so I'm not sure how I'd go about it. My teacher is really big about doing everything in functions with almost nothing in main but calls and outputs. I was taught differently last semester, so it's been a hassle not only figuring out the code, but doing it his way.
Topic archived. No new replies allowed.