0

heres my code, when I run it, most of it works, but from what I've found is that whenever the program runs through the for loop, the getinput function is being called twice.

#include <stdio.h>

char space[3][3];
int ogx = 2;
int ogy = 2;
int input;
int mx;
int my;

void printgrid(){

    printf("\n");
    printf(" %c %c %c \n %c %c %c \n %c %c %c \n", space[3][1], space[3][2], space[3]     
    [3], space[2][1], space[2][2], space[2][3], space[1][1], space[1][2], space[1][3]);
}

prints grid array

int getinput(){
    char input;
    int output;

    printf("enter move (wasd):\n");
    scanf("%c", &input);

if (input == 'w'){
        output = 1;
}
else if (input == 'a'){
    output = 2;
}
else if (input == 's'){
    output = 3;
}
else if (input == 'd'){
    output = 4;
}
else {
    printf("incorrect input, use w, a, s, or d.");
}
return output;
}

gets player input as a char of w, a, s, or d and returns it as an int

void resetgrid(){
    space[1][1] = '1';
    space[1][2] = '2';
    space[1][3] = '3';
    space[2][1] = '4';
    space[2][2] = '5';
    space[2][3] = '6';
    space[3][1] = '7';
    space[3][2] = '8';
    space[3][3] = '9';
}

defines the blank grid

void createsprite(x, y){
space[y][x] = 'x';  //x and y are reversed in the array, didn't feel like fixing
}

function creating a "sprite" at the coordinates defined in args

int calcx(){
    if (input == 2){
        ogx--;
    }
    else if (input == 4){
        ogx++;
    }
    return ogx;

}

int calcy(){
    if (input == 1){
        ogy++;
    }
    else if (input == 3){
        ogy--;
    }
    return ogy;
}

takes user input from the getinput function and calculates the x and y position after the move

int main(){

    resetgrid();
    createsprite(ogx,ogy);
    printgrid();

    for (int turns = 0; turns < 10; turns++){
        input = getinput();
        my = calcy();    
        mx = calcx();
        resetgrid();
        createsprite(mx,my);
        printgrid();

    }
    return 0;
}

What the for loop should do is, 1. get user input, 2. calculate x and y positions after input, 3. clear all past sprites from the grid, 4. create a sprite at the position calculated by calcx and calcy, and 5. print the grid with the sprite. These 5 steps are in one turn, and the loop should repeat 10 times.

What ends up happening is that the basic program works, but whenever it runs through the for loop, getinput() seems to be called twice, and the first time it is called, it prints an error because it does not let you enter input, it passes directly through.

SuperStormer
  • 4,531
  • 5
  • 20
  • 32
  • 3
    `scanf("%c", &input);` ===> `scanf(" %c", &input);` to consume the prior newline left in the prior input operation. And fyi, this problem could be replicated by stripping literally everything in this code out *except* `getinput()`, called in a simple loop from `main`. – WhozCraig Feb 15 '22 at 20:55

0 Answers0