From: Scott Worley Date: Thu, 31 Dec 2015 08:11:14 +0000 (-0800) Subject: Board input X-Git-Url: http://git.scottworley.com/slidingtile/commitdiff_plain/32688d85f745574d7bbf941985234458d2776cce?ds=inline;hp=d85437b1e3f5a8ed633a90f6e2ee14ca2f7713b5 Board input --- diff --git a/sliding_tile_lib.cc b/sliding_tile_lib.cc index 4b422c1..a4d522e 100644 --- a/sliding_tile_lib.cc +++ b/sliding_tile_lib.cc @@ -1,5 +1,7 @@ #include "sliding_tile_lib.h" +#include + signed char adjacent[BOARD_SIZE][5] = { 1, 4, -1, -1, -1, 0, 2, 5, -1, -1, @@ -18,3 +20,20 @@ signed char adjacent[BOARD_SIZE][5] = { 10, 13, 15, -1, -1, 11, 14, -1, -1, -1, }; + +std::istream& operator>>(std::istream& is, Board& board) { + for (int i = 0; i < BOARD_SIZE; i++) { + if (!is.good()) { + is.setstate(std::istream::failbit); + break; + } + if (i > 0 && is.get() != ',') { + is.setstate(std::istream::failbit); + break; + } + int numeric; + is >> numeric; + board[i] = numeric; + } + return is; +} diff --git a/sliding_tile_lib.h b/sliding_tile_lib.h index 7e6004b..8967324 100644 --- a/sliding_tile_lib.h +++ b/sliding_tile_lib.h @@ -1,8 +1,14 @@ #ifndef _SLIDING_TILE_LIB_H #define _SLIDING_TILE_LIB_H +#include + const int BOARD_DIM = 4; const int BOARD_SIZE = BOARD_DIM * BOARD_DIM; + +typedef signed char Board[BOARD_SIZE]; +std::istream& operator>>(std::istream& is, Board& board); + extern signed char adjacent[BOARD_SIZE][5]; #endif /* _SLIDING_TILE_LIB_H */ diff --git a/sliding_tile_lib_test.cc b/sliding_tile_lib_test.cc index 2050896..0bbaec3 100644 --- a/sliding_tile_lib_test.cc +++ b/sliding_tile_lib_test.cc @@ -32,3 +32,26 @@ TEST(Adjacency, Adjacency) { EXPECT_THAT(actual, testing::UnorderedElementsAreArray(expected)); } } + +TEST(Board, GoodInput) { + std::istringstream is{"15,14,9,13,3,1,12,8,0,11,6,4,7,5,2,10"}; + Board b; + is >> b; + EXPECT_FALSE(is.fail()); + EXPECT_TRUE(is.eof()); + EXPECT_THAT(b, testing::ElementsAreArray({15,14,9,13,3,1,12,8,0,11,6,4,7,5,2,10})); +} + +TEST(Board, ShortInput) { + std::istringstream is{"15,14,9,13,3,1,12,8,0,11,6,4,7,5,2"}; + Board b; + is >> b; + EXPECT_TRUE(is.fail()); +} + +TEST(Board, NonNumericInput) { + std::istringstream is{"15,14,foo,13,3,1,12,8,0,11,6,4,7,5,2,10"}; + Board b; + is >> b; + EXPECT_TRUE(is.fail()); +}