輸入名字顯示其電話號碼

運行結果:

 Enter a name to find the corresponding phone number.
 Ash Williams
 The number is: 333-2323
 Look up another name? (y/n)
 y
 Enter a name to find the corresponding phone number.
 lenove
 Name not found.
 Look up another name? (y/n)
 n 

findPhoneNumber.cpp

#include <iostream>
#include <string>

using namespace std;

const string lookupName(const string&, const string*, const string*, int);

int main() {

    string names[] = {"Michael Myers", "Ash Williams", "Jack Torrance", "Freddy Krueger"};
    string phoneNumbers[] = {"333-8000", "333-2323", "333-6150", "339-7970"};
    string targetName, targetPhone;
    char c;

    do {
        cout << "Enter a name to find the corresponding phone number.\n";
        getline(cin, targetName);
        targetPhone = lookupName(targetName, names, phoneNumbers, 4);
        if (targetPhone.length() > 0)
            cout << "The number is: " << targetPhone << endl;
        else
            cout << "Name not found.\n";
        cout << "Look up another name? (y/n)\n";
        cin >> c;
        /* 有參示例:cin.ignore(5,'\n') 當從輸入流(cin)中讀取5個字符或該字符爲'\n'時停止讀取。
         * 無參示例:cin.ignore(),僅從輸入流(cin)中讀取1個字符。
         * /
        cin.ignore(); // 將字符y或n之後的'\n'讀取並丟棄
    } while (c == 'y');

    return 0;
}

const string lookupName(const string& tN, const string n[], const string pN[], int len) {
    string pFind;
    for (int i = 0; i < len; i++) {
        if (tN == n[i])
            pFind = pN[i];
    }

    return pFind;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章