Sorting array into Alphabetic order
Jan 20, 2012 at 9:57am UTC
I'm trying to take a list of names and put them into an array so I can sort the letters into alphabetic order, so michael would become acehilm, it seems to work fine except it adds extra letter to the end of some words, here is the code:
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 32 33 34 35 36 37 38 39 40 41 42 43
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char line[10]; //to store the words
char temp;
ifstream iwords("wordlist.txt" );
if (iwords.is_open())
{
while (!iwords.eof())
{
iwords >> line; //put words from file into array
for (int i = 0; i < sizeof (line) - 1; i++)
{
for (int j = 0; j < sizeof (line) - 1; j++)
{
if (line[j] > line[j+1])
{
temp = line[j+1];
line[j+1] = line[j];
line[j] = temp;
}
}
cout << line[i]; //output sorted word
}
cout << endl;
}
iwords.close(); //close file
}
else cout << "Error! could not open file!" ;
//end of file!
}
Last edited on Jan 20, 2012 at 10:59am UTC
Jan 20, 2012 at 12:13pm UTC
don't use sizeof (line)
use strlen(line)
instead.
sizeof (line)
returns always 10 while the word itself is shorter (beware of the trailing 0). strlen() results the correct number
Topic archived. No new replies allowed.