sorting a string array

This is a discussion on sorting a string array within the C++ Programming forums, part of the General Programming Boards category; okay i need to sort a string array by the first letter of the strings. i read the input from ...

  1. #1
    The code loser
    Join Date
    Mar 2007
    Posts
    13

    sorting a string array

    okay i need to sort a string array by the first letter of the strings.
    i read the input from a file and then into a different file
    Code:
    //this program 
    //
    //program4.cpp
    //my name. (im not going to tell you this)
    
    #include <fstream> 
    #include <iostream>
    #include <string>
    
    
    using namespace std; // using standard namespace
    
    int main ()
    {
    	char file[20];
    	string stri;
    	string str[] = 100;
    	int quit =24;
    	cout << "enter the name of the input file in the format filename.txt: " ; //user determines the file to write to
    	cin >> file;
    	cout << endl;
    	fstream myfil (file);
        if (myfil.is_open())
    	{
    		quit=0;
    	}
    	else quit=1;
    	while (quit==1) // keeps the user from trying to write in a close file
        {
    	
    		cout << "file could not be opened. enter the name of another file in the format filename.txt:" ; //error message
    		cin >> file;
    		fstream myfil ("example.txt");
    		if (myfil.is_open())
    		{
    			quit=0;
    		}
    	}
    
    	for (intx=1; x<=100; x++)
    	myfil >> stri[x-1];
    
    	
    	
    	//^ here is my problem
    	//i need to sort this string
    	//
    	//
    	//
    	
    	
    	
    	
    	cout << "enter the name of the output file in the format filename.txt: " ; //user determines the file to write to
    	cin >> file;
    	
    	ofstream myfile (file);
        if (myfile.is_open())
    	{
    		quit=0;
    	}
    	else quit=1;
    	while (quit==1) // keeps the user from trying to write in a close file
        {
    	
    		cout << "file could not be opened. enter the name of another file in the format filename.txt: " ; //error message
    		cin >> file;
    		ofstream myfile ("example.txt");
    		if (myfile.is_open())
    		{
    			quit=0;
    		}
    	}
    	
    	
    
    
    	while (myfil)
    	{
    	myfil >> str;
    	myfile <<str << endl;
      
    	
    	
    	}	
    	
    		 
    	myfile.close();
    	myfil.close();// close the file
    	return 0;
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,266
    Code:
    string str[] = 100;
    I think you meant:
    Code:
    string str[100];
    Sorting is pretty easy with the help of the standard library. You can start by writing a function object that compares the first characters of two strings:
    Code:
    class CompareByFirstChar
    {
    public:
        bool operator()(const std::string& x, const std::string& y) const
        {
            return x[0] < y[0]; // Assume all strings have at least 1 character.
        }
    };
    Then, in say, your main() function you can call std::sort() from the <algorithm> header, instantiating a CompareByFirstChar function object as you do so:
    Code:
    sort(str, str + 100, CompareByFirstChar());
    Incidentally, it looks like you are not handling your files properly. You have one myfil fstream object in the scope of main(), and another in the scope of a while loop in main(). You are probably looking to write a loop along these lines:
    Code:
    string file;
    // ... read into file ...
    fstream myfil(file.c_str());
    while (!myfil)
    {
        cout << "file could not be opened. enter the name of another file in the format filename.txt:";
        cin >> file;
        myfil.clear();
        myfil.open(file.c_str());
    }
    Last edited by laserlight; 04-23-2007 at 02:50 PM. Reason: Carelessness in writing the function object.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    The code loser
    Join Date
    Mar 2007
    Posts
    13
    i need to do it without stl

    oh and the following code is giving me this error


    Code:
    while (myfil)
    	{
    	myfil >> str;
    	myfile <<str << endl;
      
    	
    	
    	}
    Code:
    error C2451: conditional expression of type 'class std::basic_fstream<char,struct std::char_traits<char> >' is illegal
            Ambiguous user-defined-conversion

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,266
    Change that to:
    Code:
    while (myfil >> str)
    {
        myfile << str << endl;
    }
    By the way, don't you think that having variables named myfil and myfile in the same scope rather... dangerous? I think you could rename myfil to an ifstream object named say, in or infile or fin (etc), and then rename myfile to out or outfile or fout (etc).
    Last edited by laserlight; 04-23-2007 at 02:56 PM.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    The code loser
    Join Date
    Mar 2007
    Posts
    13
    yay it worked. but i still need to kno how to sort an array by the first letter without the standard template library

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,266
    Well, do you know how to sort arrays in the first place?
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    The code loser
    Join Date
    Mar 2007
    Posts
    13
    i know how to do a bubble sort with an integer array

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,266
    Excellent. Are you aware that characters in a string can be treated as integers (as that is what they are, though not int)? Of course, instead of swapping integers, you would swap strings, but you can compare characters like you compare integers.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    The code loser
    Join Date
    Mar 2007
    Posts
    13
    so im guessing that the
    Code:
    if (stri[count] < stri[count+1])
    needs to be changed but here is what i came up with


    Code:
    bool swap;
    	string temp;
    	int bottom = 99;     
    	do
    	{
    		swap = false;
    		for (int count = 0; count <= bottom; count++)
    		{
    			if (stri[count] < stri[count+1])
    			{	          
    			   temp = stri[count];  
    			   stri[count] = stri[count+1];
    			   stri[count+1] = temp;
    			   swap = true; // indicates that a swap occurred
    			}
    		}
                bottom--;   
    	            
    	} while(swap != false);
                  // loop repeats until a pass through the array with
    	          // no swaps occurs

  10. #10
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,266
    If stri is an array of 100 C++ strings, then that is on the right track, though it has a few problems:
    1. There may be an array out of bounds error since your inner loop condition allows for count = bottom, but stri[100] does not exist.
    2. Since you swap when the first element is less than the second element, it means that you are sorting in reverse. Is this what you want?
    3. You are using the operator< of C++ strings. It works, but then it is more than just comparing "by the first letter of the strings".

    You might want to indent your code more nicely, e.g.,
    Code:
    bool swap;
    string temp;
    int bottom = 99;
    do
    {
        swap = false;
        for (int count = 0; count <= bottom; count++)
        {
            if (stri[count] < stri[count+1])
            {
                temp = stri[count];
                stri[count] = stri[count+1];
                stri[count+1] = temp;
                swap = true; // indicates that a swap occurred
            }
        }
        bottom--;
    } while (swap);
    // loop repeats until a pass through the array with
    // no swaps occurs
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  11. #11
    The code loser
    Join Date
    Mar 2007
    Posts
    13
    how do i sort by the first letter. oh and here is the full program

    Code:
    //this program 
    //
    //program4.cpp
    //my name. (im not going to tell you this)
    
    #include <fstream> 
    #include <iostream>
    #include <string>
    
    
    using namespace std; // using standard namespace
    
    int main ()
    {
    	char file[20];
    	string str;
    	string stri[100];
    	int quit =24;
    	cout << "enter the name of the input file in the format filename.txt: " ; //user determines the file to write to
    	cin >> file;
    	cout << endl;
    	fstream myfil (file);
        if (myfil.is_open())
    	{
    		quit=0;
    	}
    	else quit=1;
    	while (quit==1) // keeps the user from trying to write in a close file
        {
    	
    		cout << "file could not be opened. enter the name of another file in the format filename.txt:" ; //error message
    		cin >> file;
    		fstream myfil ("example.txt");
    		if (myfil.is_open())
    		{
    			quit=0;
    		}
    	}
    
    	for (int x=1; x<=100; x++)
    	myfil >> stri[x-1];
    
    
    	bool swap;
    	string temp;
    	int bottom = 99;     
    	do
    	{
    		swap = false;
    		for (int count = 0; count <= bottom; count++)
    		{
    			if (stri[count] > stri[count+1])
    			{	          
    			   temp = stri[count];  
    			   stri[count] = stri[count+1];
    			   stri[count+1] = temp;
    			   swap = true; // indicates that a swap occurred
    			}
    		}
                bottom--;   
    	            
    	} while(swap != false);
                  // loop repeats until a pass through the array with
    	          // no swaps occurs
    
    
    
    	cout << "enter the name of the output file in the format filename.txt: " ; //user determines the file to write to
    	cin >> file;
    	
    	ofstream myfile (file);
        if (myfile.is_open())
    	{
    		quit=0;
    	}
    	else quit=1;
    	while (quit==1) // keeps the user from trying to write in a close file
        {
    	
    		cout << "file could not be opened. enter the name of another file in the format filename.txt: " ; //error message
    		cin >> file;
    		ofstream myfile ("example.txt");
    		if (myfile.is_open())
    		{
    			quit=0;
    		}
    	}
    
    	for (int y =0; y<100; y++)
    	
    	{
    	str = stri[y] ;
    	myfile <<str << endl;
    	}
    	
    	
    		
    	
    		 
    	myfile.close();
    	myfil.close();// close the file
    	return 0;
    }
    Last edited by radiantarchon28; 04-23-2007 at 03:50 PM.

  12. #12
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    > if (stri[count] > stri[count+1])
    Change this to:
    Code:
    			if (stri[count][0] > stri[count+1][0])

  13. #13
    The code loser
    Join Date
    Mar 2007
    Posts
    13
    ok thnx
    Last edited by radiantarchon28; 04-23-2007 at 04:03 PM.

  14. #14
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >where did vanne go?
    It probably got bubble sorted up to element 100 of your string array, which doesn't exist. You should change your file read to a while() as Lasarlight suggested, and increment a count as each name is read. Then you can use this in your sort loop:
    Code:
    int bottom = 0;
    //
    //File read loop with bottom incremented for each read
    //
    
    	do
    	{
    		swap = false;
    		for (int count = 0; count < bottom; count++)

  15. #15
    Registered User
    Join Date
    Apr 2011
    Posts
    1

    Help PLZZ

    conditional expression of type 'class std::basic_fstream<char,struct std::char_traits<char> >' is illegal

    Hi
    i made a programe from a book i got this 1 error in this specific programe can any one plz help me out about this error.

    The code is the following:

    #include "iostream"
    #include "cstdlib"
    #include "cstdio"
    #include "ctime"
    #include "fstream"
    #include "istream"
    using namespace std;
    class shapes
    {
    public:
    virtual void draw()=0;
    virtual void save(fstream &out)=0;
    virtual void open(fstream &in)=0;
    };
    class myline : public shapes
    {
    private:
    int sx,sy,ex,ey,color;
    public:
    myline()
    {}
    myline(int x1, int y1, int x2, int y2, int clr)
    {
    sx=x1;
    sy=y1;
    ex=x2;
    ey=y2;
    color=clr;
    }
    void draw()
    {
    cout<<"Line-draw()"<<endl;
    }

    void save(fstream &out)
    {
    out<<"L"<<"\n";
    out<<sx<<""<<sy<<""<<ex<<""<<ey<<""<<color<<"\n";
    }

    void open(fstream &in)
    {

    in>>sx>>sy>>ex>>ey>>color;
    }
    };

    class myrectangle: public shapes
    {
    private:
    int sx,sy,ex,ey,color;
    public:
    myrectangle()
    {}
    myrectangle(int x1, int y1,int x2, int y2,int clr)
    {
    sx=x1;
    sy=y1;
    ex=x2;
    ey=y2;
    color=clr;
    }

    void draw()
    {
    cout<<"Rectangle-draw()"<<endl;
    }

    void save(fstream &out)
    {
    out<<"R"<<"\n";
    out<<sx<<""<<sy<<""<<ex<<""<<ey<<""<<color<<"\n";
    }
    void open(fstream &in)
    {
    in>>sx>>sy>>ex>>ey>>color;
    }
    };

    class mycircle: public shapes
    {
    private:
    int sx, sy, radius, color;

    public:

    mycircle()
    {
    }

    mycircle(int x1, int y1, int r, int clr)
    {
    sx=x1;
    sy=y1;
    radius=r;
    color=clr;
    }

    void draw()
    {
    cout<<"Circle-draw()"<<endl;
    }

    void save(fstream &out)
    {
    out<<"C"<<"\n";
    out<<sx<<""<<sy<<""<<radius<<""<<color<<"\n";
    }

    void open(fstream &in)
    {
    in>>sx>>sy>>radius>>color;
    }
    };

    struct node
    {
    void*obj;
    node*link;
    };

    class objarray
    {
    private:
    node*head;
    public:
    objarray()
    {
    head= NULL;
    }

    void add(void*o)
    {
    node*temp = new node;
    temp->obj=o;
    temp->link=NULL;
    if(head==NULL)
    head=temp;
    else
    {
    node*q;
    q=head;
    while(q->link != NULL)
    q=q->link;
    q->link=temp;
    }
    }

    void*getobj(int i)
    {
    node*q;
    q=head;

    int n;
    for (n=1; n<i; n++)
    {
    q=q->link;
    }

    return(q->link);
    }

    int getcount()
    {
    int n=0;
    node*q;
    q=head;

    while(q != NULL)
    {
    q=q->link;
    n++;
    }
    return n;
    }

    ~objarray()
    {
    node *q;

    q=head;

    while(q != NULL)
    {
    head = head->link;
    delete q;
    q=head;
    }
    }
    };

    int main(int argc, char*argv[])
    {
    fstream file;
    char choice;
    int clmum,sx,sy,ex,ey,rad;
    shapes*ptr;
    objarray arr;

    char a[2];
    int i;

    if(argc==2)
    file.open(argv[1], ios::in|ios:ut);
    while(file)
    {
    file>>a;

    if(strcmp(a,"L")==0)
    {
    myline*l = new myline();
    l->open(file);
    arr.add(l);
    }

    if(strcmp(a,"R")==0)
    {
    myrectangle *a=new myrectangle();
    a->open(file);
    arr.add(a);
    }
    if(strcmp(a,"C")==0)
    {
    mycircle*c=new mycircle();
    c->open(file);
    arr.add(c);
    }
    }

    int count = arr.getcount();
    for(i=1; i<=count; i++)
    {
    ptr=(shapes*)arr.getobj(i);
    ptr->draw();
    }

    srand((unsigned ) time(NULL));

    while(1)
    {
    cout<<endl<<"1.Line 2. Rectanle 3.Circle 4.Exit"<<endl;

    cout<<"Your Choice:";
    fflush(stdin);
    cin.get(choice);;
    clmum=rand()%16;
    sx=rand()%638;
    sy=rand()%478;
    ex=rand()%638;
    ey=rand()%478;
    rad=rand()%200;

    myline*l;
    myrectangle*a;
    mycircle*c;

    switch(choice)
    {
    case '1':
    l = new myline(sx, sy, ex,ey,clmum);
    if(l=NULL)
    exit(1);
    arr.add(l);
    cout<<"Following Line added to array"<<endl;
    cout<<"sx="<<sx<<"sy="<<sy<<"ex ="<<ex<<"ey ="<<ey<<"color ="<<clmum<<endl;
    break;

    case '2':

    a = new myrectangle(sx,sy,ex,ey,clmum);
    if(a==NULL)
    exit(1);

    arr.add(a);
    cout<<"Following Rectangle added to array"<<endl;
    cout<<"sx="<<sx<<"sy="<<sy<<"ex ="<<ex<<"ey ="<<ey<<"color ="<<clmum<<endl;
    break;

    case '3':

    c=new mycircle(sx,sy,rad,clmum);
    if(c==NULL);

    exit(1);

    arr.add(c);
    cout<<"Following Circle added to array"<<endl;
    cout<<"sx="<<sx<<"sy="<<sy<<"rad ="<<rad<<"color"<<clmum<<endl;
    break;
    case '4':

    if(argc==1)
    {

    cout<<"Enter File name:";
    char name[67];
    cin>>name;
    file.open(name,ios:ut);
    }

    count=arr.getcount();
    file.seekp(0L,ios::beg);
    file.clear();
    for(i=1; i<=count;i++)
    {
    ptr=(shapes*) arr.getobj(i);
    ptr->save(file);
    }
    file.close();
    cout<<"Array save to file......exiting"<<endl;
    exit(1);
    }
    }
    return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. sorting 2D string array
    By sureshhewa in forum C Programming
    Replies: 14
    Last Post: 07-27-2008, 02:30 PM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  3. can't assign proper values to an array of string
    By Duo in forum C Programming
    Replies: 1
    Last Post: 04-04-2005, 07:30 AM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  5. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21