Search code examples
c++arraysstringcstring

Alphabetically sorting the words


I m sorting words by comparing ascii of the 1st element of the words with another word. I have used structures to store and an array to store 5 words and then using sorting comparing asciis. Also I want it without using any character function. What wrong am I doing?

error the compilor is giving: invalid conversion from char to int, invalid array assignment, expected primary expression before int

#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;


struct Words{
char name[20];
};

int main(){

Words words[5];


for(int i=0; i<5; i++){

    cout<<"Enter the name"<<endl;
    cin>>words[i].name;

}
int temp;
//sorting

for(int i=0; i<5; i++){
//ascii code

    for(int j=0; j<4; j++){
        if(words[j+1].(int)name[0]<words[j].(int)name[0]){
            temp=words[j].name;
            words[j].name=words[j+1].name;
            words[j+1].name=temp;
        }


    }
}

cout<<endl;
//output
for(int i=0; i<5; i++){

    cout<<words[i].name<<endl;


}

return 0;
}

Solution

  • This statement

        if(words[j+1].(int)name[0]<words[j].(int)name[0]){
    

    is syntactically invalid. The correct statement will look the following way

        if( ( int )words[j+1].name[0]<( int )words[j].name[0]){
    

    However there is no any sense to make such a record because (the C++ Standard)

    The usual arithmetic conversions are performed on operands of arithmetic or enumeration type

    On the other hand if type char behave as signed char and your array can contain characters with negative values then the sorting will be invalid. I advice to rewrite the statement the following way

        if( ( unsigned char )words[j+1].name[0]<( unsigned char )words[j].name[0]){
    

    Also these statement are invalid

            temp=words[j].name;
            words[j].name=words[j+1].name;
            words[j+1].name=temp;
    

    Arrays (variable temp shall be defined as char[20]) have no the assignment operator. Either use standard C function strcpy or define the arrays as std::array<char,20>

    For example (you need include header

            strcpy( temp, words[j].name );
            strcpy( words[j].name, words[j+1].name );
            strcpy( words[j+1].name, temp );
    

    Or ( you need include header )

    struct Words{
     array<char, 20> name;
    };
    
    array<char, 20> temp;
                temp=words[j].name;
                words[j].name=words[j+1].name;
                words[j+1].name=temp;