fork(1) download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <string>
  4. #include <iomanip>
  5.  
  6. using std::cin;
  7. using std::cout;
  8. using std::endl;
  9.  
  10. void parse_as_char(std::istream& is)
  11. {
  12. char c1 = '#', c2 = '#', c3 = '#';
  13.  
  14. is.clear();
  15. is >> c1;
  16. cout << "(1) c1='" << c1 << "', is.good()=" << is.good() << ", is.eof()=" << is.eof() << endl;
  17. is >> c2;
  18. cout << "(2) c2='" << c2 << "', is.good()=" << is.good() << ", is.eof()=" << is.eof() << endl;
  19. is >> c3;
  20. cout << "(3) c3='" << c3 << "', is.good()=" << is.good() << ", is.eof()=" << is.eof() << endl;
  21. }
  22.  
  23. void parse_as_str(std::istream& is)
  24. {
  25. std::string s1 = "#", s2 = "#", s3 = "#";
  26.  
  27. is.clear();
  28. is >> s1;
  29. cout << "(1) s1=\"" << s1 << "\", is.good()=" << is.good() << ", is.eof()=" << is.eof() << endl;
  30. is >> s2;
  31. cout << "(2) s2=\"" << s2 << "\", is.good()=" << is.good() << ", is.eof()=" << is.eof() << endl;
  32. is >> s3;
  33. cout << "(3) s3=\"" << s3 << "\", is.good()=" << is.good() << ", is.eof()=" << is.eof() << endl;
  34. }
  35.  
  36. void test_parse_as_str(const char* szInput)
  37. {
  38. std::istringstream ist;
  39.  
  40. cout << __FUNCTION__ << ": Input=\"" << szInput << "\"" << endl;
  41. ist.str(szInput);
  42. parse_as_str(ist);
  43. cout << endl;
  44. }
  45.  
  46. void test_parse_as_char(const char* szInput)
  47. {
  48. std::istringstream ist;
  49.  
  50. cout << __FUNCTION__ << ": Input=\"" << szInput << "\"" << endl;
  51. ist.str(szInput);
  52. parse_as_char(ist);
  53. cout << endl;
  54. }
  55.  
  56. int main()
  57. {
  58. // ケースA)
  59. cout << "Case A)" << endl;
  60. test_parse_as_char("A B"); // Bの後ろに空白無し --> 'B' を読んだ後の is >> c3 で初めて!is.good()かつis.eof()成立(getc()と同じ挙動)
  61.  
  62. // ケースA')
  63. cout << "Case A')" << endl;
  64. test_parse_as_char("A B "); // Bの後ろに空白有り --> (同上)
  65.  
  66. // ケースB)
  67. cout << "Case B)" << endl;
  68. test_parse_as_str("A B"); // Bの後ろに空白無し --> "B" を読んだ時点で!is.good()かつis.eof()成立
  69.  
  70. // ケースC)
  71. cout << "Case C)" << endl;
  72. test_parse_as_str("A B "); // Bの後ろに空白有り --> "B" を読んだ後の is >> s3 で初めて!is.good()かつis.eof()成立(getc()と同じ挙動)
  73. }
  74.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
Case A)
test_parse_as_char: Input="A B"
(1) c1='A', is.good()=1, is.eof()=0
(2) c2='B', is.good()=1, is.eof()=0
(3) c3='#', is.good()=0, is.eof()=1

Case A')
test_parse_as_char: Input="A B "
(1) c1='A', is.good()=1, is.eof()=0
(2) c2='B', is.good()=1, is.eof()=0
(3) c3='#', is.good()=0, is.eof()=1

Case B)
test_parse_as_str: Input="A B"
(1) s1="A", is.good()=1, is.eof()=0
(2) s2="B", is.good()=0, is.eof()=1
(3) s3="#", is.good()=0, is.eof()=1

Case C)
test_parse_as_str: Input="A B "
(1) s1="A", is.good()=1, is.eof()=0
(2) s2="B", is.good()=1, is.eof()=0
(3) s3="#", is.good()=0, is.eof()=1