질문글도 많이 올라오는데 c++쓰는 사람들은 팁 하나 보고가라

scanf 쓰다가 cin을 쓰면 형식에 맞춰서 input을 받는 게 되게 어려운데, 헤더에 코드 몇 줄만 추가해주면 쉽게 할 수 있음.

#include <iostream>
#include <cstring>

//These are handy bits that go in a header somewhere template<class e, class t, int N> std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e(&sliteral)[N]) { e buffer[N-1] = {}; //get buffer in >> buffer[0]; //skips whitespace if (N>2) in.read(buffer+1, N-2); //read the rest if (strncmp(buffer, sliteral, N-1)) //if it failed in.setstate(std::ios::failbit); //set the state return in; } template<class e, class t> std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, const e& cliteral) { e buffer(0); //get buffer in >> buffer; //read data if (buffer != cliteral) //if it failed in.setstate(std::ios::failbit); //set the state return in; } //redirect mutable char arrays to their normal function template<class e, class t, int N> std::basic_istream<e,t>& operator>>(std::basic_istream<e,t>& in, e(&carray)[N]) { return std::operator>>(in, carray); }

이 코드를 컴퓨터 어딘가에 저장해놓고 include해서 쓰셈.
사용법은 다음과 같음.

int main(void)
{
int x,y;
std::cout << "Input coordinate(ex: x=12,y=15):";
std::cin >> 'x' >> '=' >> x >> ',' >> 'y' >> '=' >> y; //whitespace between format characters are allowed when skipws is set; e.g x = 12, y = 15 is allowed
std::cout << x << ", " << y << '\n';
std::cout << "Input coordinate again without whitespace(ex: x=12,y=15):";
std::cin >> "x=" >> x >> ",y=" >> y; //whitespace between format characters are NOT allowed regardless of skipws flag; e.g x = 12, y = 15 is NOT allowed, only x=12,y=15 is allowed
if(std::cin.fail())
{
std::cout << "DONT PUT WHITE SPACE!\n";
return -1;
}
std::cout << x << ", " << y << '\n';
return 0;
}

입력:
x = 12, y = 15
x=12,y=15
출력:
12, 15
12, 15

입력:
x = 12, y = 15
x = 12, y = 15
출력:
12, 15
DONT PUT WHITE SPACE!

물론 입력 형식이 복잡해지면 정규표현식을 써야겠지만 간편하게 써먹기엔 꽤 좋은 코드임.
출처:https://stackoverflow.com/questions/17244181/reading-formatted-input-using-c-streams/17244442?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

10개의 댓글

2018.04.17
혹시 c언어 구조체 좀 할 줄 아십니까?
0
2018.04.17
@Tbps
문제가 있으십니까?
0
2018.04.17
@decltype
#include <stdio.h>

struct test { int field1; };

void sub(struct test b)
{
b.field1 = 1;
}

void main()
{
struct test a = { 0 };
sub(a);
printf("%d", a.field1);
}

위 코드랑

struct test { int field1; };

void sub(struct test *b)
{
b->field1 = 1;
}

void main()
{
struct test a = { 0 }; sub(&a);
printf("%d", a.field1);
}

위코드의 결과값이 다른데 왜그런거??
0
2018.04.17
@Tbps
&a
0
2018.04.17
@구리네스
그거랑 간접접근하는건 구조체 맴버 변수 데이터가 바뀌고 그냥 접근하는건 왜 안바뀌는거랑 관계있나요?
0
2018.04.17
@Tbps
몰라 그냥 유식해보이려고 써본거야
0
2018.04.17
@Tbps
첫번째 버전은 sub 함수가 인자 b를 pass-by-value로 받음.
즉 a와는 상관없는 sub 함수 내부의 test 구조체 b가 a로부터 복사되어서 생성되고, b의 field1이 바뀐뒤에 그냥 사라짐.

두번째 버전은 sub 함수가 인자 b를 pass-by-reference로 받음(포인터).
b는 main함수 스택에 있는 a를 가리키게 되고 sub함수에서 b가 가리키는 변수를 바꾸면 main함수에 있는 a도 같이 바뀜.
swap(a,b)는 작동 안하고 swap(&a,&b)는 작동하는 원리랑 똑같음.
0
2018.04.17
@decltype
아... 그럼 일반 매개변수로 했을때는

void func(int i){
i = 1;
}

이러는거랑 똑같은 건가 보네요...

ㅇㅎ;;
0
2018.04.17
@Tbps
ㅇㅇㅇ 좀 전에 일반 매개변수로 할 때는 인자 값 그대로 가져온다 그래서 식겁했는데
구조체나 일반 매개변수나 pass-by-value로 할 때의 규칙은 똑같기 때문에 main함수에 있는 변수의 값은 안 바뀜
0
2018.04.17
@decltype
조금만 더 생각했으면 다가갔을 개념인데 덕분에 쉽게 알고갑니다 ㄳㄳ
0
무분별한 사용은 차단될 수 있습니다.
번호 제목 글쓴이 추천 수 날짜 조회 수
180587 [모바일] A25가 그렇게 별로임?? 울그락푸르락 0 12 분 전 7
180586 [컴퓨터] 독거미 도착함 5 쿠쿠N취킨 0 1 시간 전 72
180585 [잡담] 님들도 데스크테리어 해보쉴? 12 냐하하하하 0 2 시간 전 138
180584 [잡담] 논 rgb 구성으로 맞췄더니 뭔가 심심해서 2 전기모기채는신이야 0 3 시간 전 53
180583 [컴퓨터] 이거 사운드카드 죽은거냐? 3 와신상담 0 5 시간 전 106
180582 [컴퓨터] m.2케이스에 넣어서 sd카드 대신에 사용해도 괜찮아?? 6 코싸멘뚜 0 5 시간 전 141
180581 [잡담] 플스5 아무거나 사면됨?? 6 년째재수강 0 5 시간 전 116
180580 [모바일] 24 울트라 5G 512기가는 재고가 아예없네 3 마법부오러사무국장 0 6 시간 전 165
180579 [컴퓨터] 아니 바탕화면 창에 ㅈ 같은 이거 도대체 뭐라고 해요? 9 사슴만지게해줘 0 7 시간 전 206
180578 [모바일] 갤럭시 처음 써보는데 문자알림 내용표시 어떻게 해??? 17 bulusuky 1 7 시간 전 89
180577 [프로그래밍] 엥 구글 플러터 유기각 재는거임?? 4 최수연 0 8 시간 전 138
180576 [모바일] 모바일 크롬 탭창 표정 바뀜 ㅎㄷㄷ 1 살에눈나와어른의... 1 9 시간 전 150
180575 [모바일] 폰 충전기 발열이 넘 심한데 바꿔야 하나 2 우히히힣 0 11 시간 전 123
180574 [컴퓨터] i9 13900k 쓰고있는데 질문! 3 래더넉 0 14 시간 전 157
180573 [컴퓨터] 키보드 -> 방향키가 눌릴때 삐걱거림 4 뮤잉운동케겔운동... 0 16 시간 전 69
180572 [모바일] 기기변경할때 유심을 같은거쓰면 정보 그대로 보존됨? 2 마법부오러사무국장 0 17 시간 전 94
180571 [잡담] 결국 레이니 75 구매함 5 이제는끝내자 0 18 시간 전 221
180570 [컴퓨터] 이륙 허가를 요청한다! 15 와플맛 0 19 시간 전 154
180569 [컴퓨터] 찐따 컴하하 컴퓨터 구매 완료 7 69746974 0 19 시간 전 166
180568 [모바일] a34주문했는데 품절이네 ㅅㅂ 울그락푸르락 0 21 시간 전 133