1

The problem is if I enter 1, then 2 and 123. It will sort 1,123,2.
How do i make it sort 1,2,123

Item is the Records that was created. Runner is the traverser.

struct Records {
string Name;
string ID;
char Gender;
string Phone_Num;
Records *Next;
};

void SortRecords(Records* Item, Records* head, Records** Set_Head){
Records* Runner = head;

if (head == NULL){
    *Set_Head = Item;
}else if (Item->ID<head->ID){
    Item->Next=head;
}else{
    while(Item->ID>head->ID){
        if(Item->ID > Runner->ID && Runner->Next==NULL){
            Runner->Next=Item;
            break;
        }else if(Item->ID<Runner->Next->ID){
            Item->Next=Runner->Next;
            Runner->Next=Item;
            Runner=Item;
            cout<<Runner->Next->Name<<endl;
            break;
        }else{
            Runner=Runner->Next;
        }

    }

}
4
  • 2
    If string is really std::string then you're programming in C++ and should not use the C language tag. Commented Apr 4, 2018 at 4:39
  • 5
    That also explains the sorting problem you have, as strings when compared are compared lexicographically, where any string beginning with e.g. '1' will be smaller than any other string beginning with e.g. '2'. Commented Apr 4, 2018 at 4:41
  • Store your ID in an int or convert it into an int when doing the comparison. Look up how to parse strings into ints if you don't know how. Commented Apr 4, 2018 at 4:44
  • Please check the description of tags before applying them. The "c" tag explicitly tells you when it can be combined with "c++" and when not. Commented Apr 4, 2018 at 4:46

1 Answer 1

1

You can use std::stoi to compare integers not strings:

std::stoi(Item->ID) < std::stoi(Runner->Next->ID)

You might actually want to store ID as integer, not string.

If you ID can be, say "123AB", then you can extract number with:

string str = "123AB";
size_t last_index = str.find_last_of("0123456789");
string result = str.substr(0, last_index + 1); // result = "123";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.