From d9a87d61f7cdabb9b6ca7cca3c328230da3e690b Mon Sep 17 00:00:00 2001 From: KaffeeMaus Date: Fri, 26 Jan 2024 11:35:57 +0100 Subject: [PATCH] add function for user input --- src/main/c/Georg/tictactoe.c | 20 ++++++++++++++------ src/main/c/Georg/tictactoe.h | 2 ++ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/main/c/Georg/tictactoe.c b/src/main/c/Georg/tictactoe.c index 195a85e..9e12efe 100644 --- a/src/main/c/Georg/tictactoe.c +++ b/src/main/c/Georg/tictactoe.c @@ -67,18 +67,26 @@ commandFunction getCommandById( struct command* commands, int id ){ return result; } +char* getUserInput(){ + static char userInput[MAX_INPUT_LENGTH]; + printf( ":" ); + fgets(userInput, sizeof(userInput), stdin); + + size_t len = strlen(userInput); + if (len > 0 && userInput[len - 1] == '\n') { + userInput[len - 1] = '\0'; + } + + return userInput; +} + int startMenu( int code ){ if( code == 1 ){ // command test return 1; } while( GAME.currentState == 0 ){ - char userInput[50]; - printf( ":" ); - scanf( "%s", &userInput ); - - int nextState = 0; - nextState = handleCommand(userInput); + int nextState = handleCommand( getUserInput() ); if( nextState == -1 ){ printf("command not found!"); diff --git a/src/main/c/Georg/tictactoe.h b/src/main/c/Georg/tictactoe.h index f957f9c..0856e7b 100644 --- a/src/main/c/Georg/tictactoe.h +++ b/src/main/c/Georg/tictactoe.h @@ -1,6 +1,8 @@ #ifndef TICTACTOE_H #define TICTACTOE_H +#define MAX_INPUT_LENGTH 20 + struct ticTacToe{ int currentState; };