0

Apologies first up. I've been at this one part of code for about 4 hours now I've gotten so frustrated with myself.

I had a working while loop with scanf but wasn't happy with not being able to handle special characters and causing an endless loop if the user entered anything other than a numeric number.

I've attempted to switch to fgets and fputs to handle that as most replies to similar questions suggest but I'm clearly lacking the foundation of how these work. Even with some similar examples.

Issue is I can't get out of the while statement despite entering a value between 1-9. I'm guessing it's because I've failed somewhere within the char to int switch.

If I simplify the if statement to one variable it skips the loop entirely. It's quite odd.

Appreciate any advice.

    fputs("Please enter robot starting position [0-9]:", stdout);
    fgets(start_position, sizeof(start_position), stdin);
    input = (int)strtol(start_position, NULL, 10);

    while ((start_position <= 0) || (start_position >= 10)) {
        fputs("Starting position must be between 0-9 (inclusive).\n\n", stdout);
        fputs("Please enter starting position [0-9]:", stdout);
        fgets(start_position, sizeof(start_position), stdin);
        input = (int)strtol(start_position, NULL, 10);
    }
desmo
  • 1
  • 4
  • 2
    Your `while` loop is testing the value of `start_position`, which I take to be a pointer to `char` (else you're using `fgets()` very wrongly). If your compiler is not warning about the implicit conversion from pointer to integer then turn up the warning level or get a better compiler. It appears that you want to test the value of variable `input`, instead. – John Bollinger Jun 05 '21 at 13:38
  • 2
    Check the compiler warnings! `while ((start_position <= 0) || (start_position >= 10))` should be `while ((input <= 0) || (input >= 10))` – Weather Vane Jun 05 '21 at 13:38
  • Aside: you could avoid repeating the same instructions by setting `input = 0;` before the loop. – Weather Vane Jun 05 '21 at 13:40
  • You might find some useful guidance in [this question](https://stackoverflow.com/questions/58403537/). – Steve Summit Jun 05 '21 at 14:05
  • I'm a dead set moron. Why use strtol? because you need to change the char string to int. Then why use the char string to verify against integers? Idiot. Thank you everyone, I can now get some sleep and carry on tomorrow. – desmo Jun 05 '21 at 14:06
  • What is `start_position` ? a character array? – wildplasser Jun 05 '21 at 14:15
  • Start Position - will be a user determined start position on the first line of a 10x10 array used as a game board of sorts. Not looking forward to the next few steps.. – desmo Jun 06 '21 at 02:46

0 Answers0