For my assignment, I need to make a program that guesses the user's number, between 1-19 inclusively, within 5 tries. For each try, the user inputs if the number is: a) correct, b) too high, or c) too low
We are supposed to define two functions:
The first is a function that takes a number (int) as a parameter and outputs the prompt to the user that guesses that number (tells the user "Is this your number: <guess>") and shows them a menu that explains how to enter correct, high, or low.
The second function is supposed to calculate the next guess after being told if it is too high or too low.
I was able to accomplish this with nested switch statements, but I am having trouble trying to come up with the second function.
Any help is appreciated. I will try to attach my first program with the switch statements. I assume I need to generate a random number with the min and max, but I'm not sure how to do it.
#include<iostream>
using namespace std;
int main()
{
int guess = 10;
int input = 0;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch(input) {
case(1):
cout<< "Thanks for playing";
break;
case(2):
guess = 5;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch(input){
case(1):
cout<< "Thanks for playing";
break;
case(2):
guess = 3;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch (input){
case(1):
cout<< "Thanks for playing";
break;
case(2):
guess = 2;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch(input){
case(1):
cout<< "Thanks for playing";
break;
case (2):
guess = 1;
cout<< "Your guess was: "<<guess<<endl;
break;
case (3):
cout<< "Cheater..."<<endl;
break;
}
break;
case(3):
guess = 4;
cout<< "Your guess was: "<<guess<<endl;
break;
}
break;
case(3):
guess = 7;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch (input){
case (1):
cout<< "Thanks for playing";
break;
case(2):
guess = 6;
cout<< "Your guess was: "<<guess<<endl;
break;
case(3):
guess = 8;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch (input){
case (1):
cout<< "Thanks for playing";
break;
case(2):
cout<<"Cheater..."<<endl;
case(3):
guess = 9;
cout<< "Your guess was: "<< guess<<endl;
break;
}
}
break;
}
break;
case(3):
guess = 15;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch(input){
case(1):
cout<< "Thanks for playing";
break;
case(2):
guess = 13;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch (input){
case(1):
cout<< "Thanks for playing";
break;
case(2):
guess = 12;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch(input){
case(1):
cout<< "Thanks for playing";
break;
case (2):
guess = 11;
cout<< "Your guess was: "<<guess<<endl;
break;
case (3):
cout<< "Cheater..."<<endl;
break;
}
break;
case(3):
guess = 14;
cout<< "Your guess was: "<<guess<<endl;
break;
}
break;
case(3):
guess = 17;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch (input){
case (1):
cout<< "Thanks for playing";
break;
case(2):
guess = 16;
cout<< "Your guess was: "<<guess<<endl;
break;
case(3):
guess = 18;
cout<<"Is this your number: "<< guess<<endl;
cout<< "Correct? (1), High?(2), Low(3)"<<endl;
cin>> input;
switch (input){
case (1):
cout<< "Thanks for playing";
break;
case(2):
cout<<"Cheater..."<<endl;
case(3):
guess = 19;
cout<< "Your guess was: "<< guess<<endl;
break;
}
}
break;
}
break;
}
return 0;
}
Try this:
#include <iostream>
using namespace std;
#define elif else if
void guessf(int guess) {
cout << "Is this your number: " << guess << endl << "Correct? (1), High?(2), Low(3)" << endl;
}
int main(){
unsigned int range = 10, guess = 10, input = 0, i = 0;
while (i < 5 && input != 1) {
guessf(guess);
cin >> input;
if (range > 1)
range /= 2;
else
range = 1;
if (input == 1)
cout << "Thanks for playing";
elif (input == 2)
guess -= range;
else
guess += range;
}
}
What this does: the guessf() is pretty simple so we move on to the main(),the range variable is what it will be added or subtracted from the guess on each try, then, until your program does 5 tries or the guess is correct, ask user if it is correct, high or low, if it is correct cout << "Thanks for playing";, if the guess is high subtract the range and if the guess is low add the rangeto the guess. Also bcs we deal with int, the minimum value of range must be 1, bcs if it is lower nothing will ever be added or subtracted from the guess. This technique is at least something similar to "Binary Search"
If you want to remove elif, remove #define elif else if and replace elif with else if( else and if in the same line)
Also by 2 functions, you mean 2 including the main or without? This is an important thing to know
Here are some observations:
The problem set consists of numbers from 1 up to 19 i.e. range [1, 19].
The given number needs to be searched/guessed in this range.
The range is fixed i.e. it will always be [1, 19]. That means it's a sorted range.
The number of tries to guess the number is 5.
So, given the above characteristics, the Binary Search algorithm would provide an optimal solution i.e.:
Range = [1, 19]
No. of tries = 5
Worst-case performance of Binary search algorithm = O(log n)
i.e. Range = 19, O(log n) = O(log 19) = 4.25 = ~5 tries
You can do some research on the Binary Search algorithm to get familiar with it. The rest would be your logic of maintaining high, low and mid points. And, you don't need random numbers for this!
You would be using your own variation of the Binary search algorithm that guesses the number by adjusting the problem set i.e. range where the number may exist.
As far as your two functions are concerned:
The first function would show the menu and input the number to be guessed.
The second function would perform the guessing.
For the rest of the boilerplate logic, you can implement that in your main() function.
Here's a general breakdown of your code (just a synopsis, assuming you're using C++98 or C++03):
int showMenuAndInputNumber() { /* ... */ }
int guessNumber(const int n) { /* ... */ }
int main()
{
const int n = showMenuAndInput();
// validate if n is in the range [1, 19]
// given the search sorted range and the valid number,
// then using Binary search you'll need max 5 tries
// so, you don't need to keep track of the tries
// but, for simplicity, you can use tries
const int tries = 5;
for ( int t = 0; t < tries; ++t )
{
// guess the number here
// adjust the range either right or left
// according to your own Binary search algorithm's variation
}
return 0;
}
This is not meant to be a ready-made solution to your problem. This is just to provide some guidelines.
Hope this helps!
Related
I'm making a game that tests the ASCII strength of a user versus a bot. (There is also a 2 player mode but that's working fine.) The full description is given at the top of my .cpp file. As a basic breakdown, the bot opens a txt file with 500 common four letter words and inserts them into a size 500 array. It then randomly generates a number to pick a random one, and then goes through the process of tovalue() to recieve its ASCII value, where in tovalue() runs through chartoint() four times, one for each character of the word. My issue is that the program calculates the ASCII value perfectly fine of the user generated word, but always returns 0 (0000) for the botword, no matter what the word.
I've tried a few iterations of the generateword() function including using a vector but always get the same resutls. I've done a lot of digging about this and haven't quite found any solutions, although I suspect that the chartoint() function could be better optimized, just not sure how to impliment any better solutions for this specific case. Also, don't think the problem is with chartoint() since it works fine for user input, but I'm pretty sure the problem is with generateword(). Suggestions for making chartoint() would be helpful, but its not my main priority right now since I just need the program to 100% work first. Also, I've confirmed that all of the words in my .txt file are all caps and only four characters per line.
// Write the code for a game called “ASCII Strength” of a four-letter word selected by Player 1
// followed by a four-letter word selected by Player 2. The result would be the sum
//of the ASCII value of each of the letters of the selected words and whoever has higher sum (called ASCII strength) wins.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;;
int chartoint(char a) {
switch (a) {
case 'A':
return 1;
break;
case 'B':
return 2;
break;
case 'C':
return 3;
break;
case 'D':
return 4;
break;
case 'E':
return 5;
break;
case 'F':
return 6;
break;
case 'G':
return 7;
break;
case 'H':
return 8;
break;
case 'I':
return 9;
break;
case 'J':
return 10;
break;
case 'K':
return 11;
break;
case 'L':
return 12;
break;
case 'M':
return 13;
break;
case 'N':
return 14;
break;
case 'O':
return 15;
break;
case 'P':
return 16;
break;
case 'Q':
return 17;
break;
case 'R':
return 18;
break;
case 'S':
return 19;
break;
case 'T':
return 20;
break;
case 'U':
return 21;
break;
case 'V':
return 22;
break;
case 'W':
return 23;
break;
case 'X':
return 24;
break;
case 'Y':
return 25;
break;
case 'Z':
return 26;
break;
}
return 0;
}
int tovalue(string input) {
int first = chartoint(input[0]);
int second = chartoint(input[1]);
int third = chartoint(input[2]);
int fourth = chartoint(input[3]);
cout << first << second << third << fourth; // EXISTS TO TEST CALCULATION
int value = first + second + third + fourth;
return value;
}
string generateword() {
string arr[500];
ifstream file("words.txt");
if (file.is_open())
{
for (int i = 0; i < 500; i++) {
string temp;
getline(file, temp);
arr[i] = temp;
}
file.close();
}
else
{
cout << "Error: Unable to open file.";
exit(0);
}
srand(time(0));
int random_index = rand() % 500;
string random_word = arr[random_index];
return random_word;
}
int main()
{
cout << "Welcome to ASCII strength, a game where the strongest word wins!";
cout << "\nTo play, you must enter a four letter word. The program will calculate the 'ASCII strength' of your word and compare it to your opponent.";
cout << "\nWhoever has the higher sum will win!";
char another;
another = 'y';
while (another == 'y' || another == 'Y') {
cout << "\nWould you like to play against a friend, or against a bot? (F/B)";
char mode;
cin >> mode;
if (mode == 'F' || mode == 'f') {
cout << "\nPlayer 1, please input your four letter word in all caps: ";
string answer1;
cin >> answer1;
int value1;
value1 = tovalue(answer1);
cout << "\nPlayer 2, please input your four letter word in all caps: ";
string answer2;
cin >> answer2;
int value2;
value2 = tovalue(answer2);
if (value1 > value2) {
cout << "\nPlayer 1 wins!";
}
else if (value2 > value1) {
cout << "\nPlayer 2 wins!";
}
else if (value1 == value2) {
cout << "\nTie!";
}
}
else if (mode == 'B' || mode == 'b') {
cout << "\nPlease input your four letter word in all caps: ";
string answer;
cin >> answer;
int valueanswer;
valueanswer = tovalue(answer);
string botword;
botword = generateword();
cout << "\nThe bot generates a random word based on a list of popular four letter words.";
cout << "\nThe bot has generated this word: " << botword;
int valuebot;
valuebot = tovalue("botword");
cout << valueanswer << " " << valuebot; // THIS EXISTS PURELY TO TEST WHETHER THE VALUES ARE PROPERLY CALCULATING
if (valueanswer > valuebot) {
cout << "\nYou win!";
}
else if (valuebot > valueanswer) {
cout << "\nThe bot wins!";
}
else if (valueanswer == valuebot) {
cout << "\nTie!";
}
}
cout << "\nWould you like to start a new game? (y/n)";
cin >> another;
}
}
Your problem is this line:
valuebot = tovalue("botword");
Since all characters in "botword" are lowercase, you get all 0 score. You probably meant to write
valuebot = tovalue(botword);
I'm creating a student data management program in C++ and the function to insert examination marks is buggy.
The code given below is enough to recreate the buggy part of the program.
I have tried to increase the size of sub[] to 16
I have tried to insert data one after the other instead of a loop
None of the above seem to solve the problem
Menu function:
char ch;
main_menu:
clrscr();
cout << "Press the key for your choice:\n";
cout << "D -> Edit details\n";
cout << "R -> Get result\n";
cout << "I -> Insert marks\n";
cout << "E -> Exit Program";
choice:
ch = getch();
switch(ch)
{
case 'd':
//edit_nam(); Ignore this one
goto main_menu;
break;
case 'i':
ins_mar();
goto main_menu;
break;
case 'r':
//get_res(); This one is not related to the problem
goto main_menu;
break;
case 'e':
break;
default:
goto choice;
}
Insert marks function:
for(int i = 0; i < 6; i++)
{
clrscr();
cout << "Enter details of subject:" << i + 1;
cout << "\nSubject name:";
cout << "\nMarks:";
gotoxy(14, 1);
cin.getline(student.marks[i].sub, 8);
gotoxy(7,2);
cin >> student.marks[i].mark;
(i != 5) ? cout << "\nPress any key to continue..." : cout << "\nPress any key to return to menu...";
getch();
}
Student structure:
struct stu
{
char name[20];
int ID;
int cls;
mar marks[6];
};
Marks structure:
struct mar
{
char sub[8];
float mark;
}
If the code was working fine, then it would ask the user to enter the marks for all six subjects, every time the function is called in one run.
However, It is not so. In the first time of function call, everything happens in the correct manner, but it does not ask for subject name after first subject in any of the other runs.
I want the code to read through the file that is created and if they find the same string of data for student ID, or student name it will make the user enter another value before moving on. I was able to create and store the data so that it is persistent at this point but I have yet to figure out how to make the code search through the text file and find the user entered duplicates while at the same time forcing the user enter a new value.
I am unable to think of a way to accuracy show you all the code with including the entire program
#include<iostream>
#include<fstream>
#include <cstdlib>
#include <string>
#include "student.h"
#include "course.h"
#include "session.h"
using namespace std;
void fillStudents(student arg[], int size)
{
for (int i = 0; i < size; i++)
{
cout <<"Student #"<<i+1<<endl;
cout <<"=========="<<endl;
cout <<"Enter a student ID (i.e 97626): ";
cin >>arg[i].stuID;
cout <<"Enter the first name (i.e Ryan): ";
cin >>arg[i].fname;
cout <<"Enter the last name (i.e Brown): ";
cin >>arg[i].lname;
system("CLS");
}
}
void fillCourses(course c[], int size)
{
for (int i = 0; i < size; i++)
{
cout <<"Course #"<<i+1<<endl;
cout <<"=========="<<endl;
cout <<"Enter course name (i.e Data-Structures (put - instead of spaces)): ";
cin >>c[i].CourseName;
cout <<"Enter course ID (i.e CS-230 (put - instead of spaces)): ";
cin >>c[i].CourseID;
cout <<"Enter number of credits (i.e 3): ";
cin >>c[i].numberOfCredits;
system("CLS");
}
}
string CourseN(int choice, course ch[])
{
switch(choice)
{
case 1:
return ch[0].CourseID+" "+ch[0].CourseName;
break;
case 2:
return ch[1].CourseID+" "+ch[1].CourseName;
break;
case 3:
return ch[2].CourseID+" "+ch[2].CourseName;
break;
case 4:
return ch[3].CourseID+" "+ch[3].CourseName;
break;
case 5:
return ch[4].CourseID+" "+ch[4].CourseName;
break;
case 6:
return ch[5].CourseID+" "+ch[5].CourseName;
break;
case 7:
return ch[6].CourseID+" "+ch[6].CourseName;
break;
case 8:
return ch[7].CourseID+" "+ch[7].CourseName;
break;
case 9:
return ch[8].CourseID+" "+ch[8].CourseName;
break;
case 10:
return ch[9].CourseID+" "+ch[9].CourseName;
break;
default:
cout<<"Invalid decison!! Good Bye!"<<endl;
exit(0);
}
}
int creditTotal(int sel, course ch[])
{
switch(sel)
{
case 1:
return ch[0].numberOfCredits;
break;
case 2:
return ch[1].numberOfCredits;
break;
case 3:
return ch[2].numberOfCredits;
break;
case 4:
return ch[3].numberOfCredits;
break;
case 5:
return ch[4].numberOfCredits;
break;
case 6:
return ch[5].numberOfCredits;
break;
case 7:
return ch[6].numberOfCredits;
break;
case 8:
return ch[7].numberOfCredits;
break;
case 9:
return ch[8].numberOfCredits;
break;
case 10:
return ch[9].numberOfCredits;
break;
default:
cout<<"Invalid Decision!! Good Bye!"<<endl;
exit(0);
}
}
void fillSession(student arg[], course c[], session s[])
{
int c1, c2, c3, c4;
string ch1, ch2, ch3, ch4;
string startDate, endDate;
int cr1, cr2, cr3, cr4;
for (int i = 0; i < 4; i++)
{
for(int j = 0; j < 10; j++)
{
cout<<"class #"<<j+1<<" \t\t"<<c[j].CourseID<<" \t\t"<<c[j].CourseName<<" \t\t\t"<<"Credits: "<<c[j].numberOfCredits<<"\n\n";
}
cout<<"Enter your 1st class choice: ";
cin>>c1;
ch1=CourseN(c1,c);
cout<<"Enter your 2nd class choice: ";
cin>>c2;
ch2=CourseN(c2,c);
cout<<"Enter your 3rd class choice: ";
cin>>c3;
ch3=CourseN(c3,c);
cout<<"Enter your 4th class choice: ";
cin>>c4;
ch4=CourseN(c4,c);
s[i].courseID=ch1+"\n"+ch2+"\n"+ch3+"\n"+ch4;
cout<<"Enter a start date for your classes (i.e mm/dd/yyyy): ";
cin>>startDate;
s[i].startDate=startDate;
cout<<"Enter a end date for your classes (i.e mm/dd/yyyy): ";
cin>>endDate;
s[i].endDate=endDate;
cr1=creditTotal(c1, c);
cr2=creditTotal(c2, c);
cr3=creditTotal(c3, c);
cr4=creditTotal(c4, c);
s[i].totalCredits=cr1+cr2+cr3+cr4;
c1=0;
c2=0;
c3=0;
c4=0;
system("CLS");
}
}
void display_report(student s[], course c[], session se[])
{
for (int i = 0; i < 4; i++)
{
cout<<"Student ID: "<<s[i].stuID<<"\n"<<endl;
cout<<"Student Name: "<<s[i].lname<<", "<<s[i].fname<<"\n"<<endl;
cout<<"Course IDs: \n"<<se[i].courseID<<"\n"<<endl;
cout<<"Start Date: \n"<<se[i].startDate<<"\n"<<endl;
cout<<"End Date: \n"<<se[i].endDate<<"\n"<<endl;
cout<<"Total Credits: "<<se[i].totalCredits<<"\n"<<endl;
cout<<"\n"<<endl;
}
}
This is the function that I am using to create the file and continuously store the user entered information. it is within this function that I would want to try to search for the duplicate words
/**
* Writes session data to file.
* #param {session} sess sessions array.
*/
void writeSessionsToFile(session* sess, student* stude)
{
ofstream file_out("sessions.txt", ios::app);
// for now let us just assume there'll always be just 4 sessions.
for (size_t i = 0; i < 4; ++i)
{
file_out << stude[i].lname << ", "<<stude[i].fname<<"\n";
file_out << stude[i].stuID << "\n";
file_out << sess[i].courseID << "\n";
file_out << sess[i].startDate << "\n";
file_out << sess[i].endDate << "\n";
file_out << sess[i].totalCredits << "\n";
// empty line in the end of each entry.
file_out << endl;
}
}
int main()
{
cout<<"Welcome to the CS 230 Data Structures class add program!"<<endl;
cout<<"Please follow the prompt to gain a report of your courses for the year: "<<endl<<endl;
//declare and initialize 4 students
student stu[4];
fillStudents(stu, 4);
//declare and initialize 10 courses
course courses[10];
fillCourses(courses, 10);
//assign 4 courses for each student
cout<<"Enter a class selection based on the chart above (1-10), please do not choose the same class twice: "<<endl;
cout<<"Each student goes by how their information was added"<<endl<<endl;
session sessions[4];
fillSession(stu, courses, sessions);
writeSessionsToFile(sessions, stu);
//display a report showing each student with his/her courses
//show the total number of credits for each student
cout<<"Please find your name and other important information below to see your classes and credit totals: \n\n"<<endl;
cout <<"=========="<<endl;
display_report(stu, courses, sessions);
cout <<"=========="<<endl;
// instead of system(pause), pause doesn't work on linux.
cin.get();
return 0;
}
I have searched the internet as well as this website I have found function that counts the lines of the word that I am searching for, as well as functions that does find and forces the user to enter another value but I have yet to find one that I could implement in my code that will allow me to continue with the goal I have in mind
I am new to c++. I have given assignment in which i have to calculate grades and ask input from the user. If he enter wrong input i have to start program again. If the user enters correct input i have to process data and again ask if he wants to check for another calculation.I have written this code so far. I don't know how to loop back again in the program if the user enters wrong input and to start program again if it is successful. Please Give me guidance over it. Thanks.
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
//Declaring Variable
char choice;
char input;
//Promptin User to Enter his/her Choice
cout<<"Enter C or c for Computer Science: \n" ;
cout<<"Enter S or s for Software Engineering: \n";
cout<<"Enter T or T for Telecom Engineering: \n";
cout<<"Select any option from the above Menu: ";
cin>>input;
if (input != 'c' || input != 'C'){
cout<<"Invalid input! Enter the correct input option again";
}else if (input != 's' || input != 'S' ){
cout<<"Invalid input! Enter the correct input option again";
}else if (input != 't' || input != 'T' ){
cout<<"Invalid input! Enter the correct input option again";
}else if (input == 'a' || input == 'A'){
}
system("pause");
return 0;
}
You can do it using a simple do while loop:
bool valid_input = false;
do
{
// Code to read and validate the input...
} while (valid_input == false);
If the input is valid, then you set valid_input to true and the loop will end.
On an unrelated note, if you don't case about upper- or lower-case, use e.g. std::tolower so you only have to compare the letter once. E.g. std::tolower(input)
!= 'c'.
Here is the code that will prompt the user for answer as long as the answer is defined withing switch statement. ans is a variable to hold a character either 1 or 0 corresponds to the user's input (defined in switch cases or not). If defined, then ans gets 1 other wise it gets value 0. Do While loop repeats while ans is 1 (defined within switch statement).
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
char input;
char ans; //correct answer, incorrect answer
do {
cout<<"Enter C or c for Computer Science: \n" ;
cout<<"Enter S or s for Software Engineering: \n";
cout<<"Enter T or T for Telecom Engineering: \n";
cout<<"Select any option from the above Menu: ";
cin>>input;
switch (input){
case 'S':
ans = 1;
break;
case 's':
ans = 1;
break;
case 'C':
ans = 1;
break;
case 'c':
ans = 1;
break;
case 'T':
ans = 1;
break;
case 't':
ans = 1;
break;
default:
ans = 0;
}
} while (ans);
return 0;
}
User input handling is very common and can normally use similar patterns.
Basically, you re-ask for the input. You handle the valid choices and break out of the loop and you show an error when the choice is invalid and let the loop ask the input again.
Remark1: by not using switch-case here, I can break out of the loop immediately. I break immediately to avoid specifying the conditions twice or using flags, that is also why I use a loop without end-condition.
Remark2: std::flush is used to input on the prompt line. It makes sure that the prompt is shown before waiting for input.
char inp = 0;
while (true) {
std::cout << "Give input (a, b): " << std::flush;
std::cin >> inp;
inp = std::tolower(inp);
if (inp == 'a') {
std::cout << 'a\n';
break;
}
if (inp == 'b') {
std::cout << 'b\n';
break;
}
std::cout << "invalid choice (" << inp << ")";
}
The invalid choice handling can be done a bit more generic by this function, but the handling of the valid choices must still be done locally:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
char askInputChoice(const std::string& prompt, const std::vector<char>& valid)
{
char inp = 0;
while (true) {
std::cout << prompt << ": " << std::flush;
std::cin >> inp;
inp = std::tolower(inp);
if (std::find(valid.begin(), valid.end(), inp) != valid.end()) {
break;
}
std::cout << "invalid choice (" << inp << ")\n";
}
return inp;
}
int main()
{
char inp = askInputChoice("Give input (a, b)", std::vector<char>{'a','b'});
switch (inp) {
case 'a':
std::cout << "a\n";
break;
case 'b':
std::cout << "b\n";
break;
}
}
To restart the program, put it in a while loop, add a choice to quit ('q') and break when that choice is given.
Thanks Guys for All Your Support. Actually it is my First Program in C++ and sorry i have used the word guidance. Actually i have compiled it successfully. Kindly Check my program i know u do not need to but i want to know if i can add more into it to improve it.
#include <cstdlib>
#include <iostream>
#include <conio.h>
using namespace std;
int main(int argc, char *argv[])
{
//Declaring Variable
char choice;
char input;
int addTest = 0, matricMarks = 0 , interMarks = 0 , result = 0;
start: //Label
system("cls"); // Clear the Screen
//Prompting User to Enter his/her Choice
cout<<"Please Select the Degree Programme in which you are interested in to take Addmission: ";
cout<<"\nEnter C or c for Computer Science: "<<endl ;
cout<<"Enter S or s for Software Engineering: "<<endl;
cout<<"Enter T or t for Telecom Engineering: \n"<<endl;
cout<<"\nSelect any option from the above Menu: ";
cin>>input;
//Switch Statement Started
switch(input){
//Case C Started
case 'c':
case 'C':
{
cout<<"Enter your Marks in Addmission Test: ";
cin>>addTest;
cout<<"Enter your Marks in Matric Degree: ";
cin>>matricMarks;
cout<<"Enter your Marks in Intermediate Degree: ";
cin>>interMarks;
result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
if (result >= 70)
{
cout<<"\nCongratulations! You are eligible for the Computer Science degree program :)"<<endl;
}
else
{
cout<<"Sorry you Do not qualify for Computer Science Degree Programme: "<<endl;
system("pause");
}
break;
}//Case C Closeed
//Case s Started
case 's':
case 'S':
{
cout<<"Enter your Marks in Addmission Test: ";
cin>>addTest;
cout<<"Enter your Marks in Matric Degree: ";
cin>>matricMarks;
cout<<"Enter your Marks in Intermediate Degree: ";
cin>>interMarks;
result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
if (result >= 85)
{
cout<<"\nCongratulations! You are eligible for the Software Enginnering degree program :)"<<endl;
}
else
{
cout<<"\nSorry! you Do not Qualify for Software Engineering Degree: "<<endl;
system("pause");
}
break;
}//Case S Closed
//Case t Started
case 't':
case 'T':
{
cout<<"Enter your Marks in Addmission Test: ";
cin>>addTest;
cout<<"Enter your Marks in Matric Degree: ";
cin>>matricMarks;
cout<<"Enter your Marks in Intermediate Degree: ";
cin>>interMarks;
result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
if (result >= 80)
{
cout<<"\nCongratulations! You are eligible for the Telecom Engineering degree program :)"<<endl;
}
else
{
cout<<"Sorry you Do not Qualify for Telecom Enginnering Degree Programme: "<<endl;
system("pause");
}
break;
}//Case t Closed
//Default Case Started
default:
{
cout<<"\nInvalid input! Enter the correct option again: \n";
system("pause");
goto start; //Jump To Label Start
}//Deafult Case Closed
}// Switch Statement Close
//do while Loop Started
do{
cout<<"\nDo you want to check your eligibility in some other degree program y/n? : ";
cin>>choice;
if (choice=='Y'||choice=='y')
{
goto start; //jump to Label start:
}
else if (choice=='N'||choice=='n')
{
break;
}
}while(choice == 'y' || choice == 'Y');
//Do while Loop Closed
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int grade;
int aCount;
int bCount;
int cCount;
int dCount;
int fCount;
cout << "Enter the letter grades." << endl
<< "Enter the EOF character to end input." << endl;
while ((grade = cin.get()) != EOF)
{
switch (grade)
{
case 'A':
case 'a':
aCount++;
break;
case 'B':
case 'b':
bCount++;
break;
case 'C':
case 'c':
cCount++;
break;
case 'D':
case 'd':
dCount++;
break;
case 'F':
case 'f':
fCount++;
break;
case '\n':
case '\t':
case ' ':
break;
default:
cout << "Incorrect letter grade entered." << "Enter a new grade." << endl;
break;
}
}
cout << "\n\nNumber of students who received each letter grade:"
<< "\nA: " << aCount
<< "\nB: " << bCount
<< "\nC: " << cCount << "\nD: " << dCount << "\nF: " << fCount << endl;
system("PAUSE");
return 0;
}
This is an exact code provided by my C++ textbook. While I was practicing these switch statement codes by copying these codes then compile it, my Visual Studio 2010 express keep gives me an error saying that "aCount is being used without assigned..." same applies to fCount. This program should read any letter from A to F from a keyboard then increment whatever letter that was recognized. I think there should be cin>>grade somewhere in the codes but I don't find it. By the way, can "cin.get()" could work as cin>>grade??
When you are declaring your variables try giving them the value of 0 like this:
int grade = 0;
int aCount = 0;
int bCount = 0;
int cCount = 0;
int dCount = 0;
int fCount = 0;
This will ensure that you are in fact assigning a value to the variable before it is being used.
Then try to run it, I bet it works!
It is advisable for you to initialize your variables being using it. Some compiler will not even give you a warning before compilation, but assigns some "garbage values" to your un-initialize variables.
Initializing your variables to 0 is suffice in this scenario (Like what other user mentioned).
int grade=0;
int aCount=0;
int bCount=0;
int cCount=0;
int dCount=0;
int fCount=0;
By the way, can "cin.get()" could work as cin>>grade??
That depends on how you want to use it. cin.get can be used to extract a:
single character
multiple characters and store them as c-string (char array) or
store them into a stream buffer object
from the input stream.
You may realize cin.get can't accept numbers, so if you are accepting input of characters or string, it is fine. But in future, if you want it to accept numbers, just use cin >> number
An example on using cin.get()
char cStr[50];
cin.get(cStr,5); //It will take n-1 characters
cout << cStr;
//Input: abcde
//Output: abcd