프로그래밍/C++
scanf(%d 문자 입력시 무한루프
ZenoAhn
2017. 3. 20. 23:46
| |
#include <iostream> using namespace std; | |
int main() | |
{ | |
int text = 0; | |
while (1) { | |
text = 0; | |
printf("What: "); | |
cout << "scan count" << scanf("%d", &text) << endl; | |
printf("text is %d\n", text); | |
fseek(stdin, 0, SEEK_END); } | |
} | |
|
scanf 가 실패하게되면, input buffer에 있는 값을 지우지 않습니다.
그래서 다음 루프에서 scanf를 실행하게되도 input buffer에 있는 값을 그대로 사용하기 때문에
또 실패합니다.
fflush가 먹지 않는 이유는 fflush자체가 stdout 같은 출력 버퍼만을 지우도록 설계되어 있기 때문입니다.
http://stackoverflow.com/questions/25945791/character-input-in-scanfd-value
http://stackoverflow.com/questions/18170410/what-is-the-use-of-fflushstdin-in-c-programming