char vs <fstream> ?

I'm very new to C++ (less than 2 days). I've written some code to sort the letters of a word into alphabetical order. If given "jack" I expect it to return "acjk". It is working but when I tried to add more code to save the result to a file it no longer sorts (and gives very weird results):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// sort a word
#include <iostream>
#include <algorithm>
#include <fstream>
using namespace std;

int main() 
{
    int length; //store length of word
    char theword [20];
    cout << "Enter a word to be sorted: ";
    cin >> theword;
  
    for (int i=0; i<20; i++) //test length of word
                {if (theword[i] == '\0')
                length=i;}            
  
cout << "word is " << length << " letters long\n";
  
sort(theword, theword+length);
    
cout << "sorted it is " << theword << "\n";

ofstream savefile1;
savefile1.open ("sortedwords.txt");
savefile1 << theword << "\n";
savefile1.close();

system("PAUSE");
return 0;
}


When I comment out the following section to will sort properly again:
1
2
3
4
5
6
/*
ofstream savefile1;
savefile1.open ("sortedwords.txt");
savefile1 << theword << "\n";
savefile1.close();
*/


I feel I have totally missed some concept (pointer/arrays?), but I'm having trouble identifying what the exact problem is. Any advise would be very appreciated.

Thanks,
Azrad
Hi,
I am also very new to C++. I found a first problem with your code as you do not put a "break" to exit the loop when the condition (theword[i] == '\0') is satisfied. As it is now, you got the length of "theword" longer than the one read, thus passing some uninitialized garbage to the sort function. Could this be the problem? With this modification your code runs well on two systems I tried. Also, isn't sort supposed to work with iterators? It seems to be working also with pointers to char, though....
Sincerely
Max
Hi Max,

Thanks for the input. So I took your advise and changed that part to:
1
2
3
4
5
6
for (int i=0; i<20; i++) //test length of word
     {if (theword[i] == '\0')
          {length=i;
          break;
          }
     } 


Now it does work with the part that saves the file! Thanks!

Now I don't understand why it was working the way I orginally wrote it, when I commented out the part of the code that saved it to the file.

Thanks again,
Azrad
Topic archived. No new replies allowed.