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, 15DONT 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개의 댓글
무분별한 사용은 차단될 수 있습니다.
Tbps
decltype
Tbps
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);
}
위코드의 결과값이 다른데 왜그런거??
구리네스
Tbps
구리네스
decltype
즉 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)는 작동하는 원리랑 똑같음.
Tbps
void func(int i){
i = 1;
}
이러는거랑 똑같은 건가 보네요...
ㅇㅎ;;
decltype
구조체나 일반 매개변수나 pass-by-value로 할 때의 규칙은 똑같기 때문에 main함수에 있는 변수의 값은 안 바뀜
Tbps