From 32688d85f745574d7bbf941985234458d2776cce Mon Sep 17 00:00:00 2001 From: Scott Worley Date: Thu, 31 Dec 2015 00:11:14 -0800 Subject: [PATCH 1/1] Board input --- sliding_tile_lib.cc | 19 +++++++++++++++++++ sliding_tile_lib.h | 6 ++++++ sliding_tile_lib_test.cc | 23 +++++++++++++++++++++++ 3 files changed, 48 insertions(+) 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()); +} -- 2.44.1