Hello I am trying to write a program that will check the input to make sure what the user entered is an integer only. This is it basically, how would I make it check that the value was an integer, and if not, keep asking until the value is an integer.
1 2 3 4 5 6 7 8 9 10
int input = 0;
cout << "Please enter the number << endl;
cin >> input;
while(input < 0 || input != an integer)
{
cout << "Incorrect value or negative, please try again." << endl;
cout << "Please enter the number << endl;
cin >> input;
}
I know repeating the output is somewhat bad, but thats the only way I know how to do it currently. Thank you in advanced.
#include <limits>
// ...
int input;
std::cout << "Enter a number: ";
while (!(std::cin >> input) || input < 0)
{
std::cout << "Invalid or negative value, try again: ";
std::cin.clear(); // Clear error flags
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Basically, if the user enters something that's not an integer, the input will fail and cin will go into an error state (which is what we check for in our while loop).
Before we can attempt to get input again, we need to clear the error flags (line 8) and discard everything the user inputted (line 9).
In that example, it might be better if the user only has to enter 'y' (for yes) or 'n' (for no) rather than "yes" or "no".
But for other cases (and even this one, if you really want to), you can do something like
1 2 3 4 5 6 7 8 9 10
std::cout << "Enter a word: ";
std::string answer;
// Convert all characters to lowercase -- requires #include <cctype>
for (char& ch : answer)
ch = std::tolower(ch);
// Or, if you have an older compiler:
/* for (unsigned i = 0; i < answer.size(); ++i)
answer[i] = std::tolower(answer[i]); */
if (answer == "hello")
std::cout << "Hi!";
which basically just converts all characters to lowercase first before comparing it with another string.
So I have another questions. I am checking the valid input so far, at the end of my code I ask if they want to save the file as a new file. How would a make sure to check that that file does not already exist? Also if they want to modify or read the file, how do I check and throw an error if the file does not exist that they want to read, or modify?
Hmm, for checking whether a file exists or not, you could try to open it in read-only mode and see if that works or not:
1 2 3 4 5
std::ifstream readFile("file name goes here");
if (!readFile)
// File doesn't exist, or if it does, it can't be read
else
// File exists (since we have a valid input stream)
Note that if you use std::ofstream to write to a file that doesn't exist, then the file will be created automatically.
Awesome thank you, 1 more question. How do I modify my program to accept a filename that the user inputs right now it hard codes "example.txt" as a the filename and I am having a hard to getting it to accept user input on this
You can just use a std::string, like for anything else:
1 2 3 4 5 6 7 8 9
std::string filename;
std::cout << "Enter a file name: ";
std::getline(std::cin, filename);
// If your compiler supports C++11, this should work:
std::ifstream readFile(filename); // Same idea for (o)fstream
// Otherwise, if that doesn't work, this should:
std::ifstream readFile(filename.c_str());
Yeah but when i do it, for some reason it is not recognizing it in the class. Like ifstream throws an error no matching function for call to std::basic_fstream<char>::basic_fstream(std::string&)'
#include <iostream>
#include <string>
#include <fstream>
usingnamespace std;
class myClass{
public:
myClass (string fname) //constructor
{
filename = fname;
selection = 0;
input = 0;
number = 0.0;
anothernumber = 0.0;
replacement = 0.0;
newfilename = "";
choice = "";
answer = "";
}
string returnNewfile()
{
return newfilename;
}
string returnAnswer()
{
return answer;
}
int returnSelection()
{
return selection;
}
int returnInput()
{
return input;
}
double returnOtherNumber()
{
return anothernumber;
}
double returnNumber()
{
return number;
}
double returnReplace()
{
return replacement;
}
string returnChoice() //choice
{
return choice;
}
void Select()
{
cout << "Please enter 0 for read or 1 for write mode" << endl;
while (!(cin >> selection) || selection < 0)
{
cout << "Value is invalid, try again." << endl;
cin.clear(); //Clear error flag
cin.ignore();
} // end while
if (selection == 0)
{
ifstream filename ("example.txt");
if (filename.is_open())
{
while(getline(filename, line)) //Goes through the file and gets each line individually
{ //and prints out whats in it line by line.
cout << '\n' <<"This is what is in the file: " << line << endl;
}
filename.close();
}
}
elseif (selection == 1)
{
fstream filename("example.txt");
if (filename.is_open())
{
cout << "How many numbers do you want to enter? " << endl;
while (!(cin >> input) || input < 0)
{
cout << "Value is invalid, try again." << endl;
cin.clear(); //Clear error flag
cin.ignore();
} // end while
for (int i = 1; i <= input; i++) //This will check how many numbers you want to enter
{ //then will keep asking for the numbers until it reaches what you wanted.
cout << '\n' << "This is what is in the file: " << line << endl;
cout << '\n' << "Hit a to accept value, r to replace, d to delete it, or type x to accept rest of the values. " << endl;
while (!(cin >> choice))
{
cout << "Value is invalid, try again." << endl;
cin.clear(); //Clear error flag
cin.ignore();
} // end while
if (choice == "a" || choice == "A")
{
filename << line << endl;
}
if (choice == "r" || choice == "R")
{
cout << "What number do you want to replace it with? " << endl;
while (!(cin >> number) || number < 0)
{
cout << "Value is invalid, try again." << endl;
cin.clear(); //Clear error flag
cin.ignore();
} // end while
filename << number << " " << line << endl;
cout << "The number has been replaced." << endl;
}
if (choice == "d" || choice == "D")
{
number--;
cout << "Number deleted." << endl;
}
if (choice == "x" || choice == "X")
{
terminate();
}
cout <<'\n' << "Would you like to enter a new number? y or n" << endl;
cin >> answer;
if (answer == "y" || answer == "Y")
{
cout << '\n' << "Please enter the number." << endl;
while (!(cin >> anothernumber) || anothernumber < 0)
{
cout << "Value is invalid, try again." << endl;
cin.clear(); //Clear error flag
cin.ignore();
} // end while
filename << line << " ";
filename << anothernumber << endl;
}
}// end of for loop
cout << "Would you like to save the changes of the file to a new one?" << endl;
cin >> newfilename;
while (newfilename != "yes" || newfilename != "Yes" || newfilename != "YES" )
{
cout << "Value is invalid, try again." << endl;
cin.clear(); //Clear error flag
cin.ignore();
} // end while
if(newfilename == "yes" || newfilename == "Yes" || newfilename == "YES")
{
string thisfilenow;
cout << "Please enter new file name." << endl;
cin >> thisfilenow; //this will save the new data into another file leaving the old file intact.
filename << thisfilenow;
}
// while loop
}// end of filename.open if statement
filename.close();
}// end of else if selectio == 1
}//End of void select
private:
string filename;
string line;
string answer;
string newfilename;
int selection;
double myarray[10][10];
int input;
double number, replacement,anothernumber;
string choice;
};
int main()
{
string fname = "example.txt";
myClass co(fname);
co.Select();
}
Sweet that worked I forgot about the c_str() thats what happens when you stop coding.. LOL Thank you! So how would reconfigure my program to accept a file I enter instead of hardcoding the file name "example.txt" as you can see on line 74 and 86. I have messed with it a little but no luck ended up messing it up more than fixing it.