0

I'm reading the terminal input of characters with the getchar() function and from it I have to store the duration and the description of a task. What I'm trying to figure is how to discard the entire input once I see it is invalid. I'm trying something like this, but once I break out of the loop and return from the function, the next time I go into the main it keeps from where I was once the input was invalid. This is how I am reading the stdin and how I'm verifying it.

void processFunction() { ...declarations... while ((c = getchar()) && (!in || n != ' ') { ... statements ... if(c != ' ' && (c < '0' || c > '9') { ++invalid_token; break; } ... statements ... } if (invalid_token) { printf("invalid duration\n"); --invalid_token; return; } 

Now, the thing that I as, a begginer, was thinking was to run the rest of the input and discard it into a trash variable. Is this good practice? I think it's very inneficient and I would like to know another approach on how to discard an entire input once it's considered invalid.

Edit: I forgot to mention, I'm also using getchar() in the main function

Thank you so much in advance

4
  • There is nothing wrong with reading the input and throwing it away if that's what the logic requires. But you will need to define what "end of input" means (e.g newline character, EOF, space, etc). Commented Apr 2, 2021 at 22:00
  • Yes, it totally did help! Thanks a lot for taking your time to elucidate me! Commented Apr 2, 2021 at 22:06
  • It's hard to tell what your code is doing. Are you storing the previous input? If not, all your data has already been overwriten, because you only have one byte allocated on the stack. Commented Apr 2, 2021 at 22:08
  • Yes I am storing the useful data as the input is being read. Only problem is discarding the remaining of the stdin once something is invalid, I've decided to reset it by going over all of it with either fgets() or getchar() Commented Apr 2, 2021 at 22:17

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.