I am trying to make a part of a program that I can input multiple int values and the program checks if they are within the certain range of numbers, if not it prompts to input the last variable again correctly and after that continues on.
ATM the program gets "stuck" after entering an incorrect value. I also smell lots of uncovered issues...
#include <iostream>
int main()
{
// avoid magic numbers
// https://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constantsconstint MIN_TEMP = -40 ;
constint MAX_TEMP = +30 ;
const std::size_t NDAYS = 15 ;
int temperatures[NDAYS] {} ; // initialise to all zeroes
std::cout << "Give " << NDAYS << " temperatures [" << MIN_TEMP << ',' << MAX_TEMP << "]:\n" ;
for( int& t : temperatures ) // http://www.stroustrup.com/C++11FAQ.html#for
{
// repeat the loop till the value entered is within range
// note: for now, we assume that the user does enter some integer value
while( std::cout << "? " && std::cin >> t && ( t < MIN_TEMP || t > MAX_TEMP ) )
{
std::cout << "Give last temp again! Value must be in between "
<< MIN_TEMP << " and " << MAX_TEMP <<".\n" ;
}
}
}
This goes over and beyond of what I know about c++, but I will try. Can't get this to work at all. I am getting "undefined" errors for all the "t" -markings and initializing [NDAYS] to zeros is giving errors. Because I can't run this I am not sure is this complete code or do I need to add something to it?
The start of the line 19 is pretty darn cryptic to me. "while( std::cout << "? " && std::cin >> t &&" = ???
I guess you use a rather old compiler or IDE.
Consider using Visual Studio Community 2015 or 2017 which are free downloads.
An alternative is Code::Blocks 17.12
#include <iostream>
int main()
{
// avoid magic numbers
// https://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constantsconstint MIN_TEMP = -40 ;
constint MAX_TEMP = +30 ;
constint NDAYS = 15 ;
int temperatures[NDAYS] = {0}; // initialise to all zeroes
std::cout << "Give " << NDAYS << " temperatures [" << MIN_TEMP << ',' << MAX_TEMP << "]:\n" ;
for( int i = 0; i < NDAYS; i++)
{
// repeat the loop till the value entered is within range
// note: for now, we assume that the user does enter some integer value
while( std::cout << "? " && std::cin >> temperatures[i] && ( temperatures[i] < MIN_TEMP || temperatures[i] > MAX_TEMP ) )
{
std::cout << "Give last temp again! Value must be in between "
<< MIN_TEMP << " and " << MAX_TEMP <<".\n" ;
}
}
}