I've been trying to work on a program for class but for some reason when i input the number one for the program it goes to case 1 but then it doesn't let me enter a string and goes straight back to the menu. Ex) enter in 1 the result is: Enter a string: 01. Adds number but ignores anything that not a number.
If I use a regular cin statement the code will execute perfectly fine. I don't understand why it is doing this. Can somebody help?
#include <iostream>
#include <cctype>
using namespace std;
void firstChoice(char []);
int main()
{
int choice;
int answer;
const int SIZE = 100;
char line[SIZE];
do
{
cout << "1. Adds numbers but ignores anything thats not a number." << endl;
cout << "2. Count the number of consonants in a string." << endl;
cout << "3. Counts the vowels in a string." << endl;
cout << "4. Counts whitespace characters in a string." << endl;
cout << "Enter a number to access that program or 0 to end it: ";
cin >> choice;
switch(choice)
{
case 1:
cout << "\nEnter a string: ";
cin.getline(line, SIZE);
firstChoice(line);
break;
case 2:
cout << "Enter a string: ";
cin.getline(line, SIZE);
break;
case 3:
cout << "Enter a string: ";
cin.getline(line, SIZE);
break;
case 4:
cout << "Enter a string: ";
cin.getline(line, SIZE);
break;
}
}
while(choice != 0);
return 0;
}
void firstChoice(char line[])
{
int size2 = 0;
int sum = 0;
while(line[size2] != '\0')
{
if(isalpha(line[size2]))
{
line[size2] = 0;
}
sum += line[size2];
size2++;
}
cout << sum;
}
After this statement
cin >> choice;
use
#include <limits>
//...
cin >> choice;
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
Related
How can I make cin accept only a single letter in char datatypes and numbers only in double/int datatypes.
#include <iostream>
using namespace std;
int main (){
char opt;
int num1, num2, sum;
cout << "A. Addition" << endl << "B. Subtraction" << endl;
cout << "Enter option: "; cin >> opt;
//if I put "ab" here, I want to make cin only read the first letter if possible.
switch(opt){
case 'A': case 'a':{
cout << "Enter first number: "; cin >> num1; //accept numbers only
cout << "Enter second number: "; cin >> num2;//accept numbers only
sum = num1+num2;
cout << "The sum is " << sum;
break;
}
}
}
By definition, operator>> reading into a char will read in exactly 1 character, leaving any remaining input in the buffer for subsequent reading. You have to validate the read is successful and the character is what you are expecting before using it.
And likewise, operator>> reading into an int will read in only numbers. You have to validate the read is successful before using the number, and discard any unused input if the read fails to return a valid number.
Try something like this:
#include <iostream>
#include <string>
#include <limits>
using namespace std;
char ReadChar(const char* prompt) {
string s;
do {
cout << prompt << ": ";
if (!(cin >> s)) throw ...;
if (s.length() == 1) break;
//cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Enter a single character" << endl;
}
while (true);
return s[0];
}
char ReadInt(const char* prompt) {
int value;
do {
cout << prompt << ": ";
if (cin >> value) break;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Enter a valid number" << endl;
}
while (true);
return value;
}
int main() {
char opt;
int num1, num2, result;
cout << "A. Addition" << endl << "B. Subtraction" << endl;
opt = ReadChar("Enter option");
switch (opt) {
case 'A': case 'a': {
num1 = ReadInt("Enter first number");
num2 = ReadInt("Enter second number");
result = num1 + num2;
cout << "The sum is " << result << endl;
break;
}
case 'B': case 'b': {
num1 = ReadInt("Enter first number");
num2 = ReadInt("Enter second number");
result = num1 - num2;
cout << "The difference is " << result << endl;
break;
}
default: {
cout << "Invalid option" << endl;
break;
}
}
}
I am trying to code exception handling in my switch statement for a memnu in case user inputs something other than an int. Tried many different methods and still get continuous loop when user inputs a character.
I have tried using std exception but even with the include my compiler still sees error during build.
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <cctype>
using namespace std;
class Exam
{
public:
int loadExam()
{
//ifstream infile;
//string examName = exam;
ifstream infile("exam.txt");
streambuf *cinbuf = cin.rdbuf(); //save old buf
cin.rdbuf(infile.rdbuf()); //redirect std::cin to infile.txt!
string line, theQuestion, questiontype, theAnswer;
int questionvalue;
//get the number of questions from the first line in the file
getline(cin,line);
numquestions = atoi(line.c_str());
for(int count = 0; count < numquestions; count++){
getline(cin,line);
//get the next line with the question type and the value of the question
int npos = line.size();
int prev_pos = 0;
int pos = 0;
while(line[pos]!=' ')
pos++;
questiontype = line.substr(prev_pos, pos-prev_pos);
prev_pos = ++pos;
questionvalue = atoi(line.substr(prev_pos, npos-prev_pos).c_str()); // Last word
//process a true/false question
if (questiontype == "TF")
{
myQuestions[count] = new QuestionTF;
getline(cin,theQuestion);
myQuestions[count]->setQuestion(theQuestion,questionvalue);
}
//process a multiple choice question
if (questiontype == "MC")
{
myQuestions[count] = new QuestionMC;
getline(cin,theQuestion);
myQuestions[count]->setQuestion(theQuestion,questionvalue);
}
}
cin.rdbuf(cinbuf); //restore cin to standard input
return numquestions;
}
void displayExamQuestions(int numquestions)
{
string qtype;
//print out the questions that have been processed
for(int count = 0; count<numquestions;count++)
{
qtype = myQuestions[count]->getQuestionType();
cout << qtype << " " << myQuestions[count]->getValue() << "\n";
myQuestions[count]->printOptions();
cout << "\n";
}
}
private:
Question *myQuestions[10];
int numquestions;
};
int main() {
Exam myExam;
int numquestions;
int choice;
while((choice = displayMenu())!=3)
switch(choice)
{
case 1:
numquestions = myExam.loadExam();
break;
case 2:
myExam.displayExamQuestions(numquestions);
break;
default:
cout << "Invalid choice. Try again.\n\n";
}
getchar();
return 0;
}
int displayMenu()
{
int choice;
cout << "\t===================== Exam Menu =====================" << endl;
cout << "\t1. Load Exam "<<endl;
cout << "\t2. Display Exam "<<endl;
cout << "\t3. Quit"<<endl;
cout << "\t=====================================================" << "\n" << endl;
cout << "Please enter your selection: ";
cin >> choice;
cout << "\n" << endl;
return choice;
}
Require output to read "Invalid selection, Please try again" when a user inputs a character or string of alpha characters.
In this case, validation should be handled by the displayMenu function for two reasons.
The displayMenu function says that it will return an integer so it should be responsible for ensuring the user inputs a number, not a char or string.
The displayMenu lists the options so it knows how many options are available, meaning it should also check that the integer is between 1 and 3.
Infinite loop with cin when typing string while a number is expected
int displayMenu() //This function should be responsible for validating that an
// int was inputed
{
int choice;
while (true)
{
cout << "\t===================== Exam Menu =====================" << endl;
cout << "\t1. Load Exam " << endl;
cout << "\t2. Display Exam " << endl;
cout << "\t3. Quit" << endl;
cout << "\t=====================================================" << "\n" << endl;
cout << "Please enter your selection: ";
cin >> choice;
cout << "\n" << endl;
if (cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //This clears out the stream if they entered a string
//Try using cin.ignore() and inputing a string to see what happens.
}
else if (choice >= 1 && choice <= 3)
{
break;
}
}
return choice;
}
You could decouple this second part by having a displayMenu function that simply prints the menu and a second function called getInput that doesn't care what integer is inputed. It would then be up to the calling function to make sure the value is between 1 and 3.
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <cctype>
using namespace std;
void displayMenu();
int getInput();
int main() {
int numquestions;
int choice = 0;
while (choice != 3)
{
displayMenu();
while ((choice = getInput()) < 1 || choice > 3)
{
std::cout << "Please pick a value between 1 and 3\n";
displayMenu();
}
switch (choice)
{
case 1:
cout << "Case 1\n";
break;
case 2:
cout << "Case 2\n";
break;
default:
cout << "Invalid choice. Try again.\n\n";
}
}
getchar();
return 0;
}
//Only responsible for getting an int
int getInput()
{
int choice;
while (true)
{
cin >> choice;
cout << "\n" << endl;
if (cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
std::cout << "Please enter a valid number\n";
}
else
{
break;
}
}
return choice;
}
//This function only displays a menu
void displayMenu()
{
cout << "\t===================== Exam Menu =====================" << endl;
cout << "\t1. Load Exam " << endl;
cout << "\t2. Display Exam " << endl;
cout << "\t3. Quit" << endl;
cout << "\t=====================================================" << "\n" << endl;
cout << "Please enter your selection: ";
}
Im new at programming and for homework, my teacher ask me to make an option menu that does different things, but I have a problem, case 5 is supposed to end the program, but if I select 5, the do-while cycle keeps asking me if I want to do something else, when I need that if I choose 5, the program ends, how can I end with the cycle and put the option to exit the program?
Thanks, and any help is welcome
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <conio.h>
using namespace std;
int main() {
string name, lname;
int an, result;
int num;
char option;
int n, x;
time_t t, b;
char* f;
int flag = 0;
int i = 0;
do {
cout << "Option Menu";
cout << "\n1) Name and your last name";
cout << "\n2) Years of life";
cout << "\n3) First 100 numbers divisible by 3";
cout << "\n4) Date and hour";
cout << "\n5) Exit\n";
cin >> num;
switch (num) {
case 1:
cout << "\nWrite your name: ";
cin >> name;
cout << "\nWrite your last name: ";
cin >> lname;
cout << "\nYour complete name is: " << name << " " << lname;
break;
case 2:
cout << "\nWhat year you were born?: ";
cin >> an;
result = 2019 - an;
cout << "\nYou have " << result << " years\n";
break;
case 3:
for (i = 0; flag < 100; i++) {
if (i % 3 == 0) {
cout << i << "\n";
flag++;
}
}
break;
case 4:
b = time(&t);
f = ctime(&b);
printf("%s\n", f);
getch();
break;
}
cout << "\n Do you want to do something else?: ";
cin >> option;
} while (option == 's' or option == 'S');
cout << "\nGood bye :)" << endl;
system("pause");
return 0;
}
It's probably easiest to just simply use the if statement to check if num == 5 outside the switch statement and break the while loop when num is equal to 5.
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <conio.h>
using namespace std;
int main() {
string name, lname;
int an, result;
int num;
char option;
int n, x;
time_t t, b;
char* f;
int flag = 0;
int i = 0;
do {
cout << "Option Menu";
cout << "\n1) Name and your last name";
cout << "\n2) Years of life";
cout << "\n3) First 100 numbers divisible by 3";
cout << "\n4) Date and hour";
cout << "\n5) Exit\n";
cin >> num;
switch (num) {
case 1:
cout << "\nWrite your name: ";
cin >> name;
cout << "\nWrite your last name: ";
cin >> lname;
cout << "\nYour complete name is: " << name << " " << lname;
break;
case 2:
cout << "\nWhat year you were born?: ";
cin >> an;
result = 2019 - an;
cout << "\nYou have " << result << " years\n";
break;
case 3:
for (i = 0; flag < 100; i++) {
if (i % 3 == 0) {
cout << i << "\n";
flag++;
}
}
break;
case 4:
b = time(&t);
f = ctime(&b);
printf("%s\n", f);
getch();
break;
}
if (num == 5) {
break;
}
cout << "\n Do you want to do something else?: ";
cin >> option;
} while (option == 's' || option == 'S');
cout << "\nGood bye :)" << endl;
system("pause");
return 0;
}
To accomplish this task, your switch must have either a case 5: or a default: block which assigns a value other than s or S to the option variable. That will allow your program to break out of the do..while loop.
There is another problem though. The user will still be asked if he wants to do something else even if they chose the Exit option. To avoid this, you can use an extra variable (for example, a userExits boolean) to skip the part where the program asks for input after the switch.
Here is a possible solution:
// after all the variable declarations
bool userExits = false;
do {
// All menu options
cin >> num;
switch (num) {
// (...)
case 4:
b = time(&t);
f = ctime(&b);
printf("%s\n", f);
getch();
break;
case 5:
userExits = true;
break;
}
if (userExits){
option = "exit";
}
else{
cout << "\n Do you want to do something else?: ";
cin >> option;
}
} while (option == 's' or option == 'S');
cout << "\nGood bye :)" << endl;
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);
So i have a palindrome program and here are the codes:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
void palindrome();
void compareTwoInt();
bool validation(const string&);
int main()
{
int selection;
cout << "\t\t\t MENU\n";
cout << "\t\t\t ----\n";
cout << "\t\t\t1. Palindrome";
cout << "\n\t\t\t2. Compare Two Integers";
cout << "\n\t\t\t3. End program\n";
cout << "\n\t\t\tEnter your choice : ";
cin >> selection;
while (selection < 0 || selection > 4)
{
cout << "\t\t\nInvalid entry. Please enter an appropriate entry.";
cout << "\n\n \t\t\tEnter your choice: ";
cin >> selection;
}
if (selection == 1)
{
cout << "Enter a word, phrase, sentence: \n";
string input;
getline(cin, input);
string input2;
for (unsigned int i = 0; i < input.length(); i++)
{
if (isalnum(input[i]))
{
input2 += toupper(input[i]);
}
}
cout << input2 << endl;
if (validation(input2))
{
cout << "The phrase is a palindrome!" << endl;
cout << "Press <Enter> key back to menu" << endl;
}
else
{
cout << "The phrase is not a palindrome!" << endl;
cout << "Press <Enter> key back to menu" << endl;
}
fflush(stdin);
cin.get();
system("cls");
return main();
}
else if (selection == 2)
{
compareTwoInt();
fflush(stdin);
system("cls");
return main();
}
else if (selection == 3)
{
cout << "\t\t Good Bye. Press <Enter> key to End the program.\n";
}
fflush(stdin);
cin.get();
return 0;
}
void compareTwoInt()
{
int first, second;
cout << "\n\nEnter your positive integer : ";
cin >> first;
cout << "\nEnter your positive integer : ";
cin >> second;
fflush(stdin);
cin.get();
}
bool validation(const string& input)
{
return input == string(input.rbegin(), input.rend());
}
for some reason when i choose 1 for the palindrome, it doesn't let me write the words, (in another words, it doesn't let me input)
the console just says:
Enter a word, phrase, sentence:
The phrase is palindrome!
Press key back to menu
Anybody have an idea how to fix this?
Thanks in advance!
When you choose 1 for the palindrome, you hit enter. Thus your input consists of the number 1 followed by a newline. Your cin >> selection; reads the number 1 and then your getline(cin, input); reads the newline, which it interprets as an empty line. You have written no code to do anything sensible with the newline character input after the number, so nothing sensible happens.
Try typing 1foof<enter> instead. Your code will read that as a 1 followed by a line containing foof.