アドレス帳ソート(c++)

10684 ワード

アドレス帳ソート(c++)
【問題の説明】氏名、誕生日、電話番号を含む通信録の構造記録を作成する.n(n<10)人の友人の情報を入力し、年齢の大きい順に順次出力する
【入力形式】友人数n(整数、n<10)を入力し、各友人の名前(文字列)、誕生日(整数)、電話番号(文字列)を順に入力します.
【入出力サンプル例】Input n:3 Input the name,birthday,number of the 1 friend:zhang 19850403413912345678 Input the name,birthday,number of the 2 friend:wang 198221020 0571-8018448 Input the name,birthday,number of the 3 friend:qian 1984619 1360619 1360619 13609876543 wang□198221020□0571-8018448 qian□198440619□13609876543 zhang□191998509876543 zhang□19985019985050508080808080543 zhang□403□13912345678
【例説明】友人の年齢が上から下の順に各友人の情報を出力し、内容と書式は以下の通りである□誕生日□電話番号%s□%d□%s□スペースを示す
問題の難点ストレージ2として配列を呼び出す.配列はstring型として定義され、複数のアルファベットを格納できます(char型を使用すると1文字しか格納できません).
質問の回答
#include <iostream>
using namespace std;
void sort(int [],string [],string [],int);//    

int main()
{
    int n,bir[10];
    string name[10],tel[10];//      
    cout<<"Input n:";
    cin>>n;
    cout<<endl;
    for(int i=0;i<n;++i)//         
    {
        cout<<"Input the name,birthday,number of the "<<i+1<<" friend:";
        cin>>name[i]>>bir[i]>>tel[i];
        cout<<endl;
    }
    
    sort(bir,name,tel,n);//      
    return 0;
}

void sort(int bir[],string name[],string tel[],int n)
{
    for(int i=0;i<n-1;++i)//      
    {
        int index=i,temp1;
        string temp2,temp3;//    
        for(int j=index+1;j<n;++j)
            if(bir[j]<bir[index]) index=j;//  :      ,                             
        //                   (        3   )
        //              ,        ,                
        temp1=bir[i];temp2=name[i];temp3=tel[i];
        bir[i]=bir[index];name[i]=name[index];tel[i]=tel[index];
        bir[index]=temp1;name[index]=temp2;tel[index]=temp3;
    }

    for(int i=0;i<n;++i)
        cout<<name[i]<<" "<<bir[i]<<" "<<tel[i]<<endl;
}

メモ:
  • C++に文字列を入力する関数は複数あります:(1)C標準関数、文字配列に文字を格納する:char str[100];scanf("%s",str);//スペースgets(str)を含めることができない文字列を読み込みます.//1行の文字を入力して、スペースがあって、Enterキーで終わります(2)C++関数、文字の配列に格納することができて、stringクラスのオブジェクトに格納することができます:string str;cin>>str;//1列の文字を読み込んで、スペースgetline(cin,str)//1行の文字を入力し、スペースを入力して、Enterキーで終了