Hello I've been wondering how to get past the whole "program crashes when user inputs the wrong data type". After extensive amount of google searches I found out that you could use !() as an argument in a loop(or if statement) to avoid that. However by doing that I encountered another problem that I couldn't find the solution for.

When I do as the code bellow then it'll just keep going in an eternal loop. And if I was to throw in a new scanf statement inside it the program would then crash.

while(!(scanf("%d",&amount)))
   {
      printf("some explenation of what went wrong");
   }

If I try to use an if statement in a loop to simulate the same(such as the code bellow) then it also would be in an eternal loop even with an alternative scanf. I found something called fflush(0) which didn't work either(I was in the impression that cin.clear() fixed this in c++, and that fflush was C's equal to c++).

while(1)
   {
      if(!(scanf("%d",&amount)))
      {
         printf("some explenation of what went wrong");
      }
   }

So my question is, how can I make the program not crash on faulty data type and not end up in an eternal loop?

You're not the first to make this mistake about fflush() ; it sounds reasonable, but the problem is that it doesn't do what you are expecting. In C, the fflush() function only operates on output, forcing it to finish immediately rather than remain in the buffer. Applying it to an input stream has undefined results, and while some implementations do in fact do something, you can't rely on it to work portably.

As for the original problem, the best solution, sadly, is to not scanf() in the first place, but (to give one possible solution) to instead use fgets() to read the input into a string buffer, which you can then apply sscanf() to. This may sound like a strange way to do it, but it would ensure that the input doesn't get blocked up with unwanted characters, and allows more flexibility in how you parse the input.

Thanks allot for your answer! Felt it was rather overwhelming to begin with, but as I googled and searched up what fgets and sscanf was it all suddenly made sense =).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.