질문글도 많이 올라오는데 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
무분별한 사용은 차단될 수 있습니다.
번호 제목 글쓴이 추천 수 날짜 조회 수
180375 [프로그래밍] 개발자보단 엔지니어가 취업이 잘됨 iillillill 0 33 분 전 61
180374 [모바일] 갤럭시에서 에어팟쓸때 3 뽀3뽀 0 2 시간 전 78
180373 [잡담] 이거 뭐라고 적혀있는거야 6 꺄꺄룽 0 3 시간 전 107
180372 [프로그래밍] 프론트엔드 개발자 연봉 1억 넘는 사람 있어? 8 잠적자 0 4 시간 전 243
180371 [모바일] 배터리 효율 떨어지면 휴대폰도 느려지나? 4 상한가 0 6 시간 전 146
180370 [잡담] 개꿀 당근에서 만원짜리 컴 득템 7 플게이어 2 13 시간 전 495
180369 [컴퓨터] 중고로 키크론 k3 pro? 라는 키보드를 구해왔는데 10 3th3 0 14 시간 전 239
180368 [견적] 이거 에센코어 KLEVV DDR4 PC4-25600 CL22 매우 싸게 나왔는... 11 부터시작하는이세... 0 19 시간 전 190
180367 [잡담] 모니터암 설치하는데 미스테리 4 사나이테스트 0 20 시간 전 324
180366 [컴퓨터] 음향 관련 잘아는 형들 질문... 4 Marlin 0 20 시간 전 139
180365 [잡담] 애드가드 안드로이드 kt-dpi 우회 업데이트 됨 1 어무니 0 21 시간 전 166
180364 [컴퓨터] m2 ssd를 메인보드 기준으로 슬롯 1번에 있는거 2번으로 옮기... 3 오뜨 0 21 시간 전 128
180363 [잡담] 유튜브앱 구간 스킵 방식이 바꼈네?? 6 츄이로 0 21 시간 전 202
180362 [컴퓨터] 이륙 허가좀 17 사촌간부랄빨기 0 22 시간 전 170
180361 [컴퓨터] 완전 컴알못인데 이 레노버 노트북 사도 될까? 15 Fiesta 0 22 시간 전 189
180360 [잡담] 천천히 충전하는 거 폰 배터리에 더 안 좋음? 6 개돼지무한리필 0 23 시간 전 163
180359 [잡담] 메타ai 공개 3 년차html개발자 1 23 시간 전 156
180358 [컴퓨터] p41을 서브 게임저장용은 낭비인가? 8 신우철 0 1 일 전 172
180357 [정보] 해당 모니터암이 여기 모니터2개에 맞을지 모르겠습니다 2 골든베릴 0 1 일 전 129
180356 [견적] (직구) SK하이닉스 Platinum P41 2TB PCIe4.0 NVMe M.2 2280 ... 7 요기쪄 0 1 일 전 347