0

I have a program that reads integers from a file and assigns them to certain variables. I have this block of code below to error check the information that is coming from the file. If the information is not a positive integer, the if statement is supposed to catch it and reset the variable and io stream.

int quantity;
input >> quantity;
if(input.fail() || (quantity < 0)){
   quantity = 0; 
   input.clear();
   input.ignore(200, ' ');
}

However, if the information is a double, then it doesn't enter this block of code and the rest of my program stops working properly. How do I get my program to enter the if statement when a double shows up in my file?

  • 1
    Please provide a complete [mre] – pcarter Feb 04 '21 at 23:46
  • When you talk about reset I/O stream are you talking about the state of the I/O stream or the read position? – Thomas Matthews Feb 05 '21 at 00:40
  • You should read the number as a string variable, then parse it for an acceptable format. For example, having a decimal point may indicate the number is floating point. – Thomas Matthews Feb 05 '21 at 00:41
  • @ThomasMatthews If I read the number as a string, then parse it for an acceptable format, how would I turn that number into an int variable? Edit: I just looked it up I think you have to use string stream? – Hovik Ohanian Feb 05 '21 at 06:02
  • @ πάντα ῥεῖ. The linked answer has nothing to do with the question. It is not a duplicate. You should at least read the question and try to understand it – A M Feb 06 '21 at 13:32
  • The answer is: The extracor operator will extract characters, until it hits a character that cannot be converted to the requested type. Example: input contains "12.34". Then the extractor can read 12 and convert this to an integer. So, no failure. You will find still ".34" in the stream. – A M Feb 06 '21 at 13:40

0 Answers0