[[완료]]C++ cint 관련 질문

choboja의 이미지

c++ 입문자입니다.

#include<iostream>
#include <string>
 
using namespace std;
 
int main()
{
	float a = 0;
	float b = 0;
	char k;
 
	if(cin>>a)
	{
		cout << "good" << endl;
	}
	else
		cout << "error"<< endl;
 
 
	if(cin >> b)
		cout << "good job" << endl;
	else
		cout << "bad" << endl;
 
	return 0;
}

궁금한 것이 만약 처음에서 a가 float 타입인데 숫자가 아닌 캐릭터를 입력하게 되면
아래에서 입력받는 b부분은 입력을 받지 않고 그냥 bad라는 결과를 출력하게 됩니다.

제 생각은 처음 if에서 잘못된 입력이 들어오면 else에서 error라는 메시지를 출력하고 밑에서는 정상적으로 인풋을 받아야할 것 같은데요..
자동적으로 bad라는 문자를 출력하는 것이 이상하네요.
어떻게 된건지 궁금합니다.

choboja의 이미지

너무 간단해서 그런가요? ㅡㅡ;

7339989b62a014c4ce6e31b3540bc7b5f06455024f22753f6235c935e8e5의 이미지

잘못된 입력을 받으면 cin 스트림에 오류 플래그가 서게 됩니다.
따라서 그 뒤로는 그냥 입력을 안 받게 되지요.
오류가 있는지 확인하려면 cin.fail()을 호출하시면 되고, cin.clear()로 오류 플래그를 제거할 수 있습니다.

---8< 서명 -----------------
애니메이션 감상 기록 http://animeta.net/

choboja의 이미지

cin.fail()은 실패시에 1을 리턴해주네요.

그런데 cin.clear()를

cin << a;
 
(중략)
 
cin.clear();   // 추가함.
 
cin << b;

a에 캐릭터를 받고
코드 사이에 넣어도 오류 플래그가 리셋되지는 않네요?
그대로 밑에도 bad가 출력이 되네요.

그렇다면 오류가 발생하게 되면 예외처리를 해야하나요?
플래그가 리셋이 안되면 한번 입력을 잘못받으면 프로그램을 사용할 수 없는건가요??

음..

bushi의 이미지

플래그*만* 리셋됩니다.
버퍼엔 그대로 아직 남아있습니다. 버리세요. cin.ignore()

OTL

choboja의 이미지


참고 사이트
http://msdn.microsoft.com/en-us/library/71t65ya2.aspx

In this example, cin sets the fail bit on the stream when it encounters non-numeric characters. The program clears the fail bit and strips the invalid character from the stream to proceed.

음. 잘못된 입력이 들어오면 fail bit를 set시키고 그 페일 비트를 clear시키고 임의의 다른 character로 잘못된 인풋을 받아들이는 형식이네요. 음.

제 이해가 맞겠죠~ ㅎㅎ

// iostream_cin.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
 
int main()
{
   int x;
   cout << "enter choice:";
   cin >> x;
   while (x < 1 || x > 4)
   {
      cout << "Invalid choice, try again:";
      cin >> x;
      // not a numeric character, probably
      // clear the failure and pull off the non-numeric character
      if (cin.fail())
      {
         cin.clear();
         char c;
         cin >> c;
      }
   }
}

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.