6번 선행

char* strcmp(char* str1, char* str2);

각 문자열의 인스턴스를 하나씩 비교하여 두 문자열이 같은지 비교하는 함수

  • 두 문자열이 같으면 0을 리턴
  • 서로 다르다면 두 문자의 ASCII코드값의 차이를 리턴
  • str1>str2이면 양수 아니면 음수를 리턴

 

 

 

6. 문자열을 두 개 입력받고 두 개의 문자열이 같은지 검사하는 프로그램을 작성하라. 만일 같으면 "같습니다.", 아니면 "같지 않습니다."를 출력하라.

 

...더보기
// 공백 없이 입력된 문자열 읽기
#include <iostream>
#include <string>
using namespace std;
int main() {
	char newPassWord[100], confirmPassWord[100];
	cout << "새 암호를 입력하세요>>";
	cin.getline(newPassWord, 100);
	cout << "새 암호를 다시 한 번 입력하세요>>";
	cin.getline(confirmPassWord, 100);
	bool correct;
	if ((strcmp(newPassWord, confirmPassWord)) == 0)
		cout << "같습니다.\n";
	else
		cout << "같지 않습니다.\n";
}

 

 

7. 다음과 같이 "yes"가 입력될 때까지 종료하지 않는 프로그램을 작성하라. 사용자로부터의 입력은 cin.getline() 함수를 사용하라. 

 

...더보기
// 공백을 포함하는 입력된 문자열 읽기
#include <iostream>
#include <string>
using namespace std;
int main() {
	char answer[50];
	do {
		cout << "종료하고싶으면 yes를 입력하세요>>";
		cin.getline(answer, 50); // 공백이 있어도 디폴트값인 개행문자(\n) 나오기 전까지 하나의 버퍼로 인식함
		if ((strcmp(answer, "yes")) == 0) {
			cout << "종료합니다...\n";
			break;
		}
	} while (true);
}

 

 

8. 한 라인에 ';'으로 5개의 이름을 구분하여 입력받아, 각 이름을 끊어내어 화면에 출력하고 가장 긴 이름을 판별하라.

 

...더보기
// 공백을 포함하는 입력된 문자열 읽기
#include <iostream>
#include <cstring>
using namespace std;
int main() {
	cout << "5 명의 이름을 ';'으로 구분하여 입력하세요\n>>";
	char name[100], longName[100];
	int len = 0;
	for (int i = 0; i < 5; ++i) {
		cin.getline(name, 100, ';');
		cout << i + 1 << " : " << name << endl;
		if ((int)strlen(name) > len) { // 처음 0이므로 첫번째 비교는 true
			len = strlen(name);
			strcpy_s(longName, name);
		}
	}
	cout << "가장 긴 이름은 " << longName << endl;
}

 

error C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.  오류로 strcpy_s() 사용했습니다.

 

strlen()은 해당 문자열의 길이를 가져오는 함수입니다. 여기서 확인하고 가야할 점은

(구글에 strlen return type in c 라고 검색합니다)

C strlen() Prototype

size_t strlen(const char *str); The function takes a single argument, i.e, the string variable whose length is to be found, and returns the length of the string passed. Thestrlen() function is defined in <string.h> header file.

 

strlen()의 리턴 타입은 size_t라고 나와있습니다. 때문에 강제 형변환을 통해 바꿔줄 필요가 있습니다 

 

BELATED ARTICLES

more