ifstream inputFile;
string fileName;
int value, x;
// Rahter do this:
Declare them as close to the point where you use them as possible (it makes reading the code easier). Also in C++ we sometimes (quite often) use the side affects of the constructor/destructor to do work. So you don't want those firing until you need them to fire.
std::cout << "What is the file name?\n"; // Don't forget the '\n'
std::string fileName;
std::getline(std::cin, fileName);
Declare them as close to the point where you use themThe same apples for eof() as possibleit does (it makes reading the code easier)fail(). Also in C++ we sometimes (quite often)Don't use the side affects of the constructor/destructor to do workit. So you don't want those firing until you need them to firePrefer bad().
while (!inputFile.eof())
// This will result in an infinite loop if the bad bit is set.
Also note that the stream operator operator>> returns a reference to the stream. Which (as stated above) when used in a boolean context will convert itself to value that is useful using bad()
while(file >> value)
{
// Loop is entered every time the read works.
// This is because `file >> value` returns a reference to a stream.
// When a stream is used in a boolean context like while(<stream>)
// weill test itself using `bad()`
}
// Always use std::getline to read user input.
// Always do the read and test in the same condition.
// Always check for bad bit.
std::string line;
int value;
while(std::getline(std::cin, line))
{
// Successfully read a line.
// If we did not enter the loop then we reached eof.
// So now we want to check what the user entered was a number.
// So convert the user input line into a stream and read a number
// from it (or try).
std::stringstream linestream(line);
if (linestream >> value)
{
// You have successfully read a user value.
// This means the read was good.
// If there was text on the input then this would have failed.
if (value >=1 && value <= 100)
{
break; // exit the loop
}
}
// If we reach here the user either entered invalid data
// Which caused the the `bad` bit in `linestream` to be set
// or the value was out of range.
// Either way we just tell him to retry.
// Note: because we create a new linestream each attempt
// this effectively resets the `bad` bit. If you want
// mess around with the bit flags in the stream that
// is fine but I usually find this easier.
std::cout << "Hey... Whats up dumb addass you can't read? Number between 1 and 100. Try again:\n"
// The outer while loop will the try to get another value.
}
if (std::cin.eof())
{
// We failed to get a get a good value.
// The loop above exited because std::getline() failed
// This happens when we reach eof thus the value has
// not been set correctly.
return 1; // or exit(1) if appropriate.
}
std::cout << "The value was good: " << value << "\n";