this is the code i wrote for simple grading exams (im still a very beginner) but when i do a wrong input in (Grades) it doesnt go to the function i made which is called (FalseInput) to make the user able to re-enter the (Grades) any suggestions to how to solve?
and how to improve in general ?
here is an example of whats the problem :
Please Type Your Name : rafeeq
Please Insert The Grade : as (which is an input error)
you failed
thanks.
#include <iostream>
#include <string>
using namespace std;
char Name[30];
int Grades;
const int MinGrade(50);
void FalseInput() {
cout << "pleae enter the number again : ";
cin >> Grades;
if (Grades >= MinGrade) {
cout << Name << " : " << "you passed\n";
cout << Grades;
} else if (Grades < MinGrade and cin.fail() == 0) {
cout << "you failed\n";
} else if (cin.fail() == 1) {
cout << "its not a valid number\n";
cin.clear();
cin.ignore(1000, '\n');
cout << endl;
FalseInput();
}
}
int main() {
cout << "Please Type Your Name : ";
cin.getline(Name, 30);
cout << "Please Insert The Grade : ";
cin >> Grades;
if (Grades >= MinGrade) {
cout << Name << " : " << "you passed\n";
cout << "The Grade Achieved : " << Grades << "%";
} else if (Grades < MinGrade) {
cout << "you failed\n";
} else if (cin.fail() == 1) {
cout << "its not a valid number\n";
cin.clear();
cin.ignore(1000, '\n');
cout << endl;
FalseInput();
}
return 0;
}
You don't check if the extraction of an int succeeds here:
cin >> Grades;
You can check the state of the input stream after extraction like this and it needs to be the first condition or else the program will make the comparisons with MinGrade first and will get a true on Grades < MinGrade.
if(!(cin >> Grades)) {
if(cin.eof()) {
// You can't recover the input steam from eof so here you need
// to handle that. Perhaps by terminating the program.
}
cin.clear();
cin.ignore(1000, '\n');
cout << endl;
FalseInput();
} else if(Grades >= MinGrade) {
cout << Name << " : " << "you passed\n";
cout << "The Grade Achieved : " << Grades << "%";
} else if(Grades < MinGrade) {
cout << "you failed\n";
}
You do have a lot of unnecessary code duplication and you also use an array of char to read the name - but you have included <string> so I assume you're familiar with std::string. I suggest using that.
Simplification:
#include <iostream>
#include <limits>
#include <string>
int main() {
const int MinGrade = 50;
std::string Name;
int Grades;
std::cout << "Please Type Your Name : ";
if(std::getline(std::cin, Name)) {
while(true) {
std::cout << "Please Insert The Grade : ";
if(!(std::cin >> Grades)) {
if(std::cin.eof()) {
std::cout << "Bye bye\n";
break;
}
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "That's not a valid number!\nPlease enter the "
"number again!\n";
} else if(Grades >= MinGrade) {
std::cout << Name << " : " << "you passed\n";
std::cout << "The Grade Achieved : " << Grades << "%\n";
break;
} else { // no need to check "Grades < MinGrade" here
std::cout << "you failed\n";
break;
}
}
}
}
What is happening: When that string "as" is attempted to write to the integer Grades, cin.fail() is set and Grades has the default of 0 written to it (I think that's right)
C++ cin reading string into int type returns 0
All-in-All: Input validation is needed BEFORE you check it's values.
Here is one approach, check if cin was able to successfully convert:
https://www.hackerearth.com/practice/notes/validating-user-input-in-c/
Another approach would be to read cin into a string instead of int, then you can control how to convert/cast it to whatever form you want (more work, but being that you are new - you will learn a lot doing this).
Secondary Note: Your string of 50 characters for name - imagine what would happen if you wrote 60 characters of input. There will be more data than the container can hold, thus writing past the bounds and into his neighbor (could cause a segment fault, or worse - crazy unexpected behavior)
Why does this work? Using cin to read to a char array smaller than given input
Related
I made this for an assignment but even if I enter a valid input from the desired range I still get prompted. This is happening to both input prompts. I suspect the problem is in the while blocks of the setupGame function.
#include <iostream>
using namespace std;
bool setupGame(int numberRef, int triesRef);
int main(){
cout<<"hello world";
setupGame(4,4);
cout<<"enough";
}
//SETUP GAME FUNCTION
bool setupGame(int numberRef, int triesRef) {
do {
cout << "ENTER A NUMBER BETWEEN 1 and 100" << endl;
cin >> numberRef;
cin.clear();
//your code here
cout << "You entered: " << numberRef << endl;
if (numberRef==-1) {
cout << "You do not want to set a number " << endl;
cout << "so you stopped the program" << endl;
}
else if(numberRef >=1 && numberRef <=100)
do {
cout << "ENTER TRIES BETWEEN 3 and 7" << endl;
cin >> triesRef;
cin.clear();
//cin.ignore( '\n');
cout<< "You entered: "<< triesRef<< endl;
if (triesRef==-1) {
cout << "You do not want to set tries. ";
cout << "so you stopped the program" << endl;
} else if(triesRef <= 3 && triesRef >= 7){
cout<<"Number of tries should be between 3 and 7";
}
}
while(numberRef >=1 && numberRef <=100);{
return true;
}
}
while(triesRef >= 3 && triesRef <= 7);{
return true;
} }
You're tangling yourself up with these nested loops. Your prompt keeps printing because the while loop:
while(numberRef >=1 && numberRef <=100)
is going to keep repeating it's preceding do block until you enter a value less than 1 or greater than 100, same goes for the last while loop as well.
I assume you're using cin.clear() to flush the previous input, if you are then stop it, that is not the purpose of cin.clear(). It's instead use to clear the error state of cin. Please thoroughly read up on it here.
Below is the code to achieve what you want, please observe how I implemented the while loops after each cin prompt to ensure that a valid character is entered.
#include <iostream>
#include <fstream>
using namespace std;
bool setupGame(int numberRef, int triesRef);
int main(){
cout<<"hello world";
setupGame(4,4);
cout<<"enough";
}
//SETUP GAME FUNCTION
bool setupGame(int numberRef, int triesRef) {
cout << "ENTER A NUMBER BETWEEN 1 and 100" << endl;
cin >> numberRef;
while((numberRef < 1 || numberRef > 100 || cin.fail()) && numberRef != -1) {
cin.clear(); // Used to clear error state of cin
cin.ignore(); // Might want to ignore the whole line
cout<<"Number should be between 1 and 100, or -1 , please try again: ";
cin>>numberRef;
}
cout << "You entered: " << numberRef << endl;
if (numberRef==-1) {
cout << "You do not want to set a number " << endl;
cout << "so you stopped the program" << endl;
}
if(numberRef >=1 && numberRef <=100) {
cout << "ENTER TRIES BETWEEN 3 and 7" << endl;
cin >> triesRef;
while(triesRef < 3 || triesRef > 7 || cin.fail()) {
cin.clear(); // Used to clear error state of cin
cin.ignore(); // Might want to ignore the whole line
cout<<"Tries should be between 3 and 7 , please try again: ";
cin>>triesRef;
}
cout<< "You entered: "<< triesRef<< endl;
if (triesRef==-1) {
cout << "You do not want to set tries. ";
cout << "so you stopped the program" << endl;
return false;
}
}
}
hey guys kind of new to the programming world and I know you should read in all input as a string but this is just a simple program and I'm having a brain fart I think but here is my question......why when I press q to quit am i getting an infinite loop and how would I condense the while loops because that looks gross
here is what I have so far
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int grade;
char quit = 'a';
cout << "Input your grade (0-100): ";
cout << endl;
cin >> grade;
while (grade < 0) {
cout << "If you have a negetive grade....drop out! otherwise enter another grade" << endl;
cin >> grade;
}
while (quit != 'q') {
while (grade < 0) {
cout << "If you have a negetive grade....drop out! otherwise enter another grade" << endl;
cin >> grade;
}
if (grade == 100) {
cout << "You got a perfect grade!" << endl;
cout << "Letter grade: A" << endl;
}
else if (grade >= 90 && grade <= 100) {
cout << "Letter grade: A" << endl << endl;
}
else if (grade >= 80 && grade <= 89) {
cout << "Letter grade: B" << endl << endl;
}
else if (grade >= 70 && grade <= 79) {
cout << "Letter grade: C" << endl << endl;
}
else if (grade >= 60 && grade <= 69) {
cout << "Letter grade: D" << endl << endl;
}
else if (grade < 60) {
cout << "Letter grade: F" << endl << endl;
}
else {
cout << "Invalid grade!" << endl;
}
cout << " would you like to enter another grade? or press q to quit" << endl;
cin >> grade;
}
system("pause");
return 0;`enter code here`
}
Because of grade var. You declared grade as int.
If you type correct int, it works well, but If you type another char ex:) q or f, function cin cannot recognize q or f as int type.
If char input, cin pass own process.
You have to change grade type into char to recognize char and int inputs both.
If you want to use only one input flow, this implementation code will help you.
int _tmain(int argc, _TCHAR* argv[])
{
char c_input[32] = {0};
cin>>c_input;
while(atoi(c_input) < 0)
{
cout<<"If you have a negative grade....drop out! otherwise enter another grade" << endl;
cin>>c_input;
}
while(c_input[0] != 'q')
{
while(atoi(c_input) < 0)
{
cout<<"If you have a negative grade....drop out! otherwise enter another grade" << endl;
cin>>c_input;
}
cout<<c_input;
cout<<"Would you like to enter another grade? or press q to quit" << endl;
cin>>c_input;
}
return 0;
}
Minimal, verifiable example:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int grade;
char quit = 'a';
cout << "Input your grade (0-100): ";
cout << endl;
cin >> grade;
while (quit != 'q') {
cout << " would you like to enter another grade? or press q to quit" << endl;
cin >> grade;
}
system("pause");
return 0;`enter code here`
}
See the problem with quit?
edit
What I have done is remove (most of) the lines that have nothing to do with quit or the loop.
At this point you should notice that the loop never changes quit.
If you are having trouble with a program, one of the best ways to figure out what is wrong is to get rid of everything that doesn't have anything to do with the error. In time, you'll be able to do this using only your mind. Duuude!
while i'm at it
The correct way to handle user input is to get it as a string, then convert it to what you want.
For example:
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
template <typename T>
T string_to( const std::string& s )
{
T value;
std::istringstream ss( s );
ss >> value >> std::ws;
if (!ss.eof()) throw std::invalid_argument("T string_to()");
return value;
}
int main()
{
std::cout << "Enter a number or 'q': ";
std::string s;
getline( std::cin, s );
if (s == 'q')
{
std::cout << "Good job! You entered 'q'.\n";
}
else
{
try
{
double x = string_to <double> ( s );
std::cout << "Good job! You entered '" << x << "'.\n";
}
catch (const std::exception& e)
{
std::cout << "Foo, you didn't obey instructions and made me " << e.what() << ".\n";
}
}
}
Not under standing looping for arrays. Looping through all of grab some or search. Can someone explain the process? Thanks in advance. Sorry if duplicate. I looked around and couldnt find a solid explaination that I could understand.
#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void allContacts(string names[], string phones[])
{
cout << "Showing all contacts... Press Q to go back to main menu" << endl;
}
void addName(string names[], string phones[])
{
bool keepGoing;
string input;
beginning:
for (int i = 0; i < sizeof(names); i++)
{
cout << "Enter contact name: ";
cin >> names[i];
cout << "Enter contact number: ";
cin >> phones[i];
cout << "Do you have another contact to add? y or no" << endl;
cin >> input;
if(input == "y" || input == "Y")
{
goto beginning;
}
if(input == "n" || input == "N")
{
cout << "Contacts you have entered: " << endl;
cout << names[i] << " : " << phones[i] << endl;
}
}
}
void searchName(string names[], string phones[])
{
string name;
cout << "Enter Name: ";
cin >> name;
cout << "Search for a name or Press Q to go back to main menu" << endl;
for (int i = 0; i < sizeof(names); i++){
if (name == names[i])
{
cout << counter << names[i] << " 's phone number is: " << phones[i] << endl;
} else {
cout << "No results found";
}
}
}
int main()
{
string names[100];
string phones[100];
int choice;
cout << "============================" << endl;
cout << "=== Welcome to PhoneBook ===" << endl;
cout << "============================" << endl;
cout << "1- Add a New Contact" << endl;
cout << "2- Search By Name" << endl;
cout << "3- Display All" << endl;
cout << "0- Exit" << endl;
cout << "Select a number: " << endl;
cin >> choice;
switch(choice)
{
case 1:
addName(names, phones);
break;
case 2:
searchName(names, phones);
break;
case 3:
allContacts(names, phones);
break;
case 0:
cout << "Exiting PhoneBook...";
break;
}
}
In C++ arrays lose attributes when passed to functions. Those attributes are capacity and size (number of filled slots). You will need to pass this additional information for each array:
void addName(string names[], unsigned int names_capacity, unsigned int names_size,
string phones[], unsigned int phones_capacity, unsigned int phones_size)
To get around this, you can use std::vector. The std::vector knows its capacity and size, so you don't have to pass additional attributes to your function.
Also, if you use tolower or toupper before you compare, you only need to make one comparison:
char input;
cout << "Do you have another contact to add? y or n" << endl;
cin >> input;
input = toupper(input);
if(input == 'Y')
When using strings, you can convert them to all uppercase or all lowercase by using std::transform, such as:
std::transform(input.begin(),
input.begin(), input.end(),
tolower);
I am currently taking a C++ programming class and am working on a project in which I have to create a fairly simple movie database. My code essentially works as intended yet in certain cases it causes the main menu to loop infinitely and I cannot figure out why. I brought this to my teacher and he cannot explain it either. He gave me a workaround but I would like to know if anyone can see the cause of the problem. Full code is as follows:
#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct MovieType
{
string title;
string director;
int year;
int length;
string rating;
};
MovieType addMovie() {
MovieType newMovie;
cout << "Movie title :";
getline(cin, newMovie.title);
cout << "Director :";
getline(cin, newMovie.director);
cout << "Year :";
cin >> newMovie.year;
cout << "Length(in minutes) :";
cin >> newMovie.length;
cout << "Rating :";
cin >> newMovie.rating;
cout << endl;
return newMovie;
}
void listMovie(MovieType movie) {
cout << "______________________________________" << endl;
cout << "Title : " << movie.title << endl;
cout << "Director : " << movie.director << endl;
cout << "Released : " << movie.year << endl;
cout << "MPAA Rating : " << movie.rating << endl;
cout << "Running time : " << movie.length << " minutes" << endl;
cout << "______________________________________" << endl;
}
void search(vector<MovieType> movieVector) {
string strSearch;
cout << endl << "Search title: ";
getline(cin, strSearch);
for (int c = 0; c < movieVector.size(); c++) {
if (movieVector.at(c).title == strSearch)
listMovie(movieVector.at(c));
}
}
int main() {
bool quit = 0;
vector<MovieType> movieVector;
while (quit == 0) {
char selection = 'f';
cout << "Main Menu:" << endl;
cout << "'a' - Add movie" << endl;
cout << "'l' - List movies" << endl;
cout << "'s' - Search by movie title" << endl;
cout << "'q' - Quit" << endl;
cout << "Please enter one of the listed commands:";
cin >> selection;
cin.ignore();
cout << endl;
if (selection == 'a')
movieVector.push_back(addMovie());
else if (selection == 'l') {
for (int c = 0; c < movieVector.size(); c++) {
listMovie(movieVector.at(c));
}
}
else if (selection == 's') {
search(movieVector);
}
else if (selection == 'q')
quit = 1;
}
return 0;
}
When an unexpected input type is entered during the addMovie function(like entering text for the int type year), it just runs through the function then loops through the menu infinitely. It appears to me that the code just stops even looking at the input stream. I have tried using cin.ignore() in many different places but it doesn't matter if there is nothing left in the stream it just keeps going.
I am using NetBeans to compile my code.
I really have no idea why it behaves like this otherwise I would offer more information but I am just curious as to why this happens, because as I said before, my professor doesn't even know why this is happening.
Any help or insight is greatly appreciated.
cin enters an error state where cin.fail() is true. In this state it just ignores all input operations. One fix is to clear the error state, but better, only use getline operations on cin, not formatted input.
E.g., instead of
cin >> newMovie.year;
… do
newMovie.year = stoi( line_from( cin ) );
… where line_from can be defined as
auto line_from( std::istream& stream )
-> std::string
{
std::string result;
if( not getline( stream, result ) )
{
// Throw an exception or call exit(EXIT_FAILURE).0
}
return result;
}
Disclaimer: code untouched by compiler.
Sorry for the lack of previous explanation to my school's assignment. Here's what I'm working with and what I have / think I have to do.
I have the basic structure for populating the address book inside an array, however, the logic behind populating a text file is a bit beyond my knowledge. I've researched a few examples, however, the implementation is a bit tricky due to my novice programming ability.
I've gone through some code that looks relevant in regard to my requirements:
ifstream input("addressbook.txt");
ofstream out("addressbook.txt");
For ifstream, I believe implementing this into the voidAddBook::AddEntry() would work, though I've tried it and the code failed to compile, for multiple reasons.
For ostream, I'm lost and unsure as to how I can implement this correctly. I understand basic file input and output into a text file, however, this method is a bit more advanced and hence why I'm resorting to stackoverflow's guidance.
#include <iostream>
#include <string.h> //Required to use string compare
using namespace std;
class AddBook{
public:
AddBook()
{
count=0;
}
void AddEntry();
void DispAll();
void DispEntry(int i); // Displays one entry
void SearchLast();
int Menu();
struct EntryStruct
{
char FirstName[15];
char LastName[15];
char Birthday[15];
char PhoneNum[15];
char Email[15];
};
EntryStruct entries[100];
int count;
};
void AddBook::AddEntry()
{
cout << "Enter First Name: ";
cin >> entries[count].FirstName;
cout << "Enter Last Name: ";
cin >> entries[count].LastName;
cout << "Enter Date of Birth: ";
cin >> entries[count].Birthday;
cout << "Enter Phone Number: ";
cin >> entries[count].PhoneNum;
cout << "Enter Email: ";
cin >> entries[count].Email;
++count;
}
void AddBook::DispEntry(int i)
{
cout << "First name : " << entries[i].FirstName << endl;
cout << "Last name : " << entries[i].LastName << endl;
cout << "Date of birth : " << entries[i].Birthday << endl;
cout << "Phone number : " << entries[i].PhoneNum << endl;
cout << "Email: " << entries[i].Email << endl;
}
void AddBook::DispAll()
{
cout << "Number of entries : " << count << endl;
for(int i = 0;i < count;++i)
DispEntry(i);
}
void AddBook::SearchLast()
{
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0;i < count;++i)
{
if(strcmp(lastname, entries[i].LastName) == 0)
{
cout << "Found ";
DispEntry(i);
cout << endl;
}
}
}
AddBook AddressBook;
int Menu()
{
int num;
bool BoolQuit = false;
while(BoolQuit == false)
{
cout << "Address Book Menu" << endl;
cout << "(1) Add A New Contact" << endl;
cout << "(2) Search By Last Name" << endl;
cout << "(3) Show Complete List" << endl;
cout << "(4) Exit And Save" << endl;
cout << endl;
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
return 0;
}
int main (){
Menu();
return 0;
}
As it currently stands, I'm still stuck. Here's where I believe I should start:
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
//save first name
//save last name
//save dob
//save phone number
//save email
//exit
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
Somehow, during menu option 4 the array should dump the data into a .txt file and arrange it in a way that it can be easily imported upon reloading the program. I'm a little confused as to how I can store the array data from each character array into a .txt file.
Well first, if the input is coming from the file input, then instead of doing cin >> x you would have to do input >> x. If it's coming from standard input (the keyboard), then you can use cin.
Also, your else if statement should be something like this:
while (true)
{
// ...
else if (num == 4)
{
for (int i = 0; i < AddressBook.count; ++i)
{
AddBook::EntryStruct data = AddressBook.entries[i];
out << data.FirstName << " " << data.LastName
<< std::endl
<< data.Birthday << std::endl
<< data.PhoneNum << std::endl
<< data.Email;
}
}
break;
}