본문 바로가기

언어/C++

4장 7번 -이름으로 전화번호 검색하기

#include <iostream>
#include <string>
using namespace std;

class Person {
	string name;
	string tel;
public :
	string getName() { return name; }
	string getTel() { return  tel; }
	void set( string name, string tel) { this->name = name; this->tel = tel; }
};

int main() {
	int n;
	Person p[3];
	string name, number;

	cout << "이름과 전화 번호를 입력해 주세요" << endl;
	for(int i=0; i<3; i++) {
	cout << "사람 " << i+1 << ">> ";
	cin >> name >> number;
	p[i].set( name, number);
	}
	cout << "모든 사람의 이름은 ";
	for(int i=0; i<3; i++)
		cout << p[i].getName() << " ";

	cout << endl << "전화번호를 검색합니다. 이름을 입력하세요>>";
	cin >> name;
	for(int i=0; i<3; i++)
		if( p[i].getName() == name ) n = i;
	cout << "전화 번호는 " << p[n].getTel() << endl;
#include <iostream>
#include <string>

using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class Person{
	private:
		string name;
		string phone;
	public:
		string getPhone(){
			return phone;
		}
		string getName(){
			return name;
		}
		void setPhone(string phone){
			this->phone=phone;
		}
		void setName(string name){
			this->name=name;
		}
};

int main(int argc, char** argv) {
	
	string per;
	string pho;
	Person person[3];
	cout << "이름과 전화번호를 입력해주세요 "<< endl;
	cout << "사람 1 >> ";
	cin>> per >> pho;
	person[0].setName(per);
	person[0].setPhone(pho);
	cout << "사람 2 >> ";
	cin>> per >> pho;
	person[1].setName(per);
	person[1].setPhone(pho);
	cout << "사람 3 >> ";
	cin>> per >> pho;
	person[2].setName(per);
	person[2].setPhone(pho);
	
	cout<< "모든 사람의 이름은 ";
	for (int i=0; i<3; i++){
		cout<<person[i].getName() << " ";
	}
	string name;
	cout << "전화번호를 검색합니다. 이름을 입력하세요 >> ";
	cin>>name;
	
	for(int i=0; i<3; i++){
		if(name==person[i].getName()){
			cout << "전화번호는 "<< person[i].getPhone() ;
		}
	}
		
	return 0;
}