Viettel Solutions
Viettel Solutions

Reputation: 1489

How to separate and arrange firstname from fullname string in C++

I have:

struct student{ 
  string name, 
  float GPA 
}; 

I want to arrange name in alphabetical order ( firstname, if firstname is the same, arrange through lastname );

So I think I need a separateFirstName function and a separateLastName function, but I don't know which value these functions return. If it's a string, how can I use it when I compare ( use it many times)

For example:

struct student{ 
    string name, 
    float GPA 
}; 

student Student[n];

void input(student Student[], int n){ ... };

Now, I want to arrange Student[i].name ( with i is from 0 to n) in alphabetical order

The first, I'll compare the firstname of Student[i].name, if they're the same, I'll compare the their lastname, if they're still the same, I'll arrange them randomly

for example:

  1. Nguyen Nhu Anh

  2. So Van Anh

  3. Sa Hi Ha

  4. Vo Duc Hung Son

So I think I need a separateFirstName function and separateLastName function

if string s="Vo Duc Hung Son";

then the first name is Son and the last name is Vo

But the thing was, I don't know which value these functions should return. If it's a string, how can I use it when I compare ( use it many times );

Thank you in advance

Upvotes: 0

Views: 1107

Answers (2)

Buddy
Buddy

Reputation: 84

I am not sure if I understand. But you have string name, for example: name = "Dennis Bond" and you want two strings. firstname = "Dennis" and secondname = "Bond"?

void split_name (string name, string& firstname, string& secondname){
    istringstream is(name);
    is >> firstname >> secondname;

}


void split_name (string name, vector<string>& split){
        istringstream is(name);
        string word;

        while (is >> word ) split.push_back(word);
}

Upvotes: 0

foobar
foobar

Reputation: 2941

struct Name{ 
  string first, 
  string last 
}; 

struct student{ 
  Name name, 
  float GPA 
}; 

Now you can write a function to compare name.first and name.last

Upvotes: 1

Related Questions