GetLine() 함수 

문제점 1) 가나다 라마바 사아자 라고 입력이 되었다고 치면 cin 또는 scanf로 입력 받을 시 가나다에서 끊기고 만다.

해결 : getline 함수를 이용

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>

using namespace std;

int main()
{
 
	char name[20];
	char dessert[20];
	
	cout << "name" << endl;
	cin.getline(name, 20);  //20글자 까지 받을 수 있다.
	cout << "dessert" << endl;
	cin.getline(dessert, 20);

	cout << "good" << dessert;
	cout << "dessert " << name << "sir " << endl;

	return 0;
}

 

문제점 2) 위의 코드로 입력 받을 시 한글이 무조건 깨진다.

이유 : ASCIII (거의 100%이거 때문임) ->

해결 : 멀티바이트 문자 집합 이용 (거의 100% 이게 해결법임)

단, 해당 문자 집합을 이용하면 그에 맞는 함수도 가져가야한다.

한글을 출력하기 위해서는 로케일 설정을 한국으로 바꿔줘여한다.

 

전체 로케일 설정

  • locale::global(locale("kor"));

부분 로케일 설정

  • wcout.imbue(locale("kor"));

코드

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>

using namespace std;

int main()
{
	wcout.imbue(locale("kor"));//한국으로 지역설정
	wcin.imbue(locale("kor")); 
	wchar_t name[20];
	wchar_t dessert[20];
	
	wstring str1;
	wstring str2; 

	wcout << "name" << endl;
	wcin.getline(name, 20);
	wcout << "dessert" << endl;
	wcin.getline(dessert, 20);

 
	wcout << "good" << dessert;
	wcout << "dessert " << name << "sir " << endl;


	return 0;
}

 

만약 wchar_t가 아닌 string에 담고 싶다면 string 대신 wstring을 사용한다.

코드 

	wcout.imbue(locale("kor"));//한국으로 지역설정
	wcin.imbue(locale("kor"));
    
	wstring str1;
	getline(wcin, str1);

 

 

 

'Algorithm > Algorithm_Tip' 카테고리의 다른 글

[Java 입출력] StringTokenizer  (0) 2020.09.08
[JAVA 입력 TIP]  (0) 2020.09.08
[탐색] 이분탐색 lower_bound, upper_bound  (0) 2020.07.21
순열&조합  (0) 2020.07.13
입력 팁  (0) 2020.06.28

+ Recent posts