0

Im trying to do this: if the value is greater than 50 or less than -50, or not an integer, than cin again the value (until it is valid)

for (size_t i = 0; i < cities; i++)
{
    for (size_t j = 0; j < days; j++)
    {
        cout << "temperature(" << i + 1 << ',' << j + 1 << ") = ";
        cin >> *(temperatures + i * days + j);
        while (!(*(temperatures + i * days + j) > 50 && *(temperatures + i * days + j) < -50))
        {
            cin.clear();
            cin.ignore();
            cout << "temperature(" << i + 1 << ',' << j + 1 << ") = ";
            cin >> *(temperatures + i * days + j);
        }
    }

if i write a number greater than 50, or less than -50 it works.

But if i write eg.:

temperature(1,1) = covid

than the next row:

temperature(1,1) = temperature(1,1) = temperature(1,1) = temperature(1,1) = temperature(1,1) = 

How can i fix this?

1
  • This StackOverflow answer includes source code for function get_int, a robust function that inputs an integer from std::cin. get_int handles all the usual errors that can happen with std::cin, and loops until a valid integer is entered. Commented Oct 26, 2023 at 15:06

1 Answer 1

1

The problem is that you are testing the value of *(temperatures + i * days + j) even when the input has failed. Plus you are using ignore incorrectly (only ignoring one character instead of all outstanding characters). Plus you have overly complex code

Here's a better version

#include <limits> // for std::numeric_limits

cout << "temperature(" << i + 1 << ',' << j + 1 << ") = ";
int temp;
while (!(cin >> temp) || temp < -50 || temp > 50)
{
     cin.clear();
     cin.ignore(numeric_limits<streamsize>::max(), '\n');
     cout << "temperature(" << i + 1 << ',' << j + 1 << ") = ";
}
temperatures[i * days + j] = temp;

I used a new variable temp to simplify the code. I included cin >> temp in the while loop condition thereby only checking temp if the input has succeeded, and I used cin.ignore(numeric_limits<streamsize>::max(), '\n'); to ignore all characters remaining in the input.

Note this probably isn't perfect. If you entered say 10deg then the input would succeed (temp would equal 10) even though the input has non-digits in it. If you want to do input validation properly then the only real way is to read the input as a string, and test the string, before converting to an integer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.