2014-02-24 6 views
0

stuType 클래스에() strcmp와하는 비교를 할 수있는 문자 배열을받을 것으로 예상) (대안은 알파벳 순으로 정렬 문자열

#include<iostream> 
#include<fstream> 
#include<cstdlib> 
#include<cstring> 

#include"stuType.h" 

using namespace std; 

/*Loads the elements of the object instance with data from the input file.*/ 
void load(istream &input, stuType Student[], int *size); 

/*Used in combination with the shellSort method to exchange the values of two variables in the class object.*/ 
void exchange(stuType &a, stuType &b); 

/*Sorts the objects in ascending order by comparing the values of the lname strings between object indices.*/ 
void shellSort(stuType Student[], int size); 

int main() { 

    stuType Student[10]; 

    int size; 

    char inputFile[200]; 
    char outputFile[200]; 

    ifstream input; 
    ofstream output; 

    cout<<"[INPUT_FILE]: "; 
    cin>>inputFile; 

    cout<<"[OUTPUT_FILE]: "; 
    cin>>outputFile; 

    input.open(inputFile); 
    output.open(outputFile); 

    if (input.fail()) { 
     cerr<<"\n[FILE] Error opening '"<<inputFile<<"'"<<endl; 
     exit(1); 
    } 

    if (output.fail()) { 
     cerr<<"\n[FILE] Error opening '"<<outputFile<<"'"<<endl; 
     exit(1); 
    } 

    load(input, Student, &size); 
    shellSort(Student, size); 

    return 0; 
} 

void load(istream &input, stuType Student[], int *size) { 

    int length = 0, i = 0; 

    float gpa; 
    string social; 
    string fname; 
    string lname; 

    while(input >> social >> fname >> lname >> gpa) { 
     cout<<"[Node::Load] Setting 'social' for index ["<<i<<"] to "<<social<<endl; 
     Student[i].set_ssn(social); 
     cout<<"[Node::Load] Setting 'fname' for index ["<<i<<"] to "<<fname<<endl; 
     Student[i].set_fname(fname); 
     cout<<"[Node::Load] Setting 'lname' for index ["<<i<<"] to "<<lname<<endl; 
     Student[i].set_lname(lname); 
     cout<<"[Node::Load] Setting 'gpa' for index ["<<i<<"] to "<<gpa<<endl; 
     Student[i].set_gpa(gpa); 
     cout<<"[Node::Load] Incrementing 'length'..."<<endl; 
     length++; 
     cout<<"[Node::Load] Incrementing 'i'..."<<endl; 
     i++; 
    } 

    cout<<"==================================="<<endl; 
    for (int i = 0; i<length; i++) { 
     cout<<"[ENTRY] Index: "<<i<<" | SSN: "<<Student[i].get_ssn()<<" | fname: "<<Student[i].get_fname()<<" | lname: "<<Student[i].get_lname()<<" | gpa: "<<Student[i].get_gpa()<<endl; 
    } 
    cout<<"==================================="<<endl; 

    *size = length; 
} 

void exchange(stuType &a, stuType &b) { 

    stuType *temp; 

    *temp = a; 
    a = b; 
    b = *temp; 

    delete temp; 
} 

void shellSort(stuType Student[], int size) { 

    int gap = size/2; 
    bool passOK; 

    while(gap>0) { 
     passOK = true; 

     for(int i = 0; i<size-gap; i++) { 
      if (strcmp(Student[i].get_lname(), Student[i+gap].get_lname)>0) { 
       cout<<"[Node::Sort] Exchanging Index ["<<i<<"] with Index ["<<i+gap<<"]..."<<endl; 
       exchange(Student[i], Student[i+gap]); 
       passOK = false; 
      } else if (strcmp(Student[i].get_lname(), Student[i+gap].get_lname())==0) { 
       if (strcmp(Student[i].get_fname(), Student[i+gap].get_fname())>0) { 
        cout<<"[Node::Sort] Exchanging Index ["<<i<<"] with Index ["<<i+gap<<"]..."<<endl; 
        exchange(Student[i], Student[i+gap]); 
        passOK = false; 
       } 
      } 
     } 

     if (passOK) { 
      gap /= 2; 
     } 
    } 
} 

을 strcmp를하지만 이후 문자열을 사용하고 있습니다. 그렇게 할 수 없습니다. 대안이란 무엇입니까? 변수 'lname'을 비교해야하며 Student [i] .get_lname()이 Student [i + gap] .get_lname()보다 큰 경우 true를 반환해야합니다. 그런 다음 exchange 함수가 호출되어 객체의 로컬 변수 값을 교환합니다. 객체는 'lname'변수의 값에 따라 오름차순으로 정렬되어야하며 'fname'변수는 비교되는 두 개의 lname이 동일한 경우에만 참조되어야합니다.

+0

배열에 사용되는. std :: string은 <와 =를 재정 의하여 유용한 정보를 제공하므로 비교를 위해 <또는 =를 사용할 수 있습니다. –

+0

문자열 인수를 취하는 세터는 문자열의 복사본이 아닌'const 문자열 '을 취해야합니다. 학생을 읽기위한 입력 연산자를 정의했습니다. 왜 사용하지 않니? 당신의'exchange' 함수는 다소 헤비급입니다. (적어도'{string t = a; a = b; b = t;}'와 비교하면 C++ 11의'swap' 기술을 사용하지 않습니다. std :: swap (a, b)')? –

답변

1

C++ 문자열 implementations of operators < and > 제공, 그래서 당신은 strcmp 대신 사용할 수 있습니다 :와 배열을 비교하는 <또는 = 그냥 메모리 위치가 아닌 내용을 비교하기 때문에 필요 STRCMP

std::string a = "hello"; 
std::string b = "world"; 
if (a < b) { 
    cout << a << " is less than " << b << endl; 
} 
+0

그렇다면 strcmp()를 완전히 사용하지 않고 < > 또는 ==을 사용하여 두 문자열을 비교하면 사전 순으로 정렬됩니까? –

+0

@AdamChubbuck, Lexicographically, 실제로, 그러나 충분히 가깝습니다. – chris

+1

@AdamChubbuck'<' and '>'은 대소 문자를 구분하여 문자열을 사전 식으로 비교합니다. 대문자와 소문자가 ASCII로 표현되는 방식 때문에 대문자는 소문자보다 먼저 정렬됩니다 (예 :'Z' <'a'). – dasblinkenlight

관련 문제