I'm reading the book programming principles and practice using C++ and the book has introduced the concept of switch statement and an example of what we can do when we want to perform the same action for a series of case labels :
cout << "Please enter a digit : ";
char a = 0;
cin >> a;
switch (a) {
case '0': case '2': case '4': case '6': case '8':
cout << "is even\n";
break;
case '1': case '3': case '5': case '7': case '9':
cout << "is odd\n";
break;
default:
cout << "is not a digit\n";
break;
}
The compiler doesn't report any error but when i execute the program if I enter the value 11 for example the program prints out : is odd. Why ? I expected to see : is not a digit but I can't understand where the problem is. This problem happens also if I enter the value 999 or some other values, why ?
You read a single character, '1'. 1 is odd.
The next character is still there to be read.
cout << "Please enter a digit : ";
You are asking user to enter a digit. Why are you storing it in char?:
char a = 0;
You need to store it in an int:
int a = 0;
Then all you cases have chars:
case '0': case '2': case '4': case '6': case '8':
This should be changed to ints:
case 0: case 2: case 4: case 6: case 8:
Similarly change for other cases.
Related
Code for a blackjack card counting program.
the issue is that it does not exit the while loop upon receiving no cin input from the user.
for example)
User would input x chars and then hit enter to exit the while loop.
#include<iostream>
using namespace std;
int main(){
int count = 0;
char currcard;
cout<<"Enter cards seen on table: "<<endl;
while (cin>>currcard)
{
switch (currcard)
{
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
count++;
break;
case '7':
case '8':
case '9':
break;
case 'A':
case 'J':
case 'Q':
case 'K':
count--;
break;
default:
cout<<"Invalid Entry";
break;
}
}
cout <<"Current count: "<< count << endl;
//user enter cards seen on table and if below 7 increment
//based on count the program returns if you should hit or quit
return 0;
}
Expecting program to exit when enter is hit by user
You can use cin.get() like this.
while (cin>>currcard)
{
// your logic
if (cin.get() == '\n') {
break;
}
}
In this way, your input is supposed to be something like 1 2 3 4 A J Q ending with Enter.
EDIT
As OP wants undetermined length of input, I suggest to switch the input itself from char to std::string.
This way access is gained to more intuitive and effective I\O operations:
#include <iostream> // std::cin, cout, endl
#include <string> // std::string: can omit this line
#include <cctype> // isspace(): can omit
int main(){
int count = 0;
std::string currcard{""};
std::cout << "Enter cards seen on table: "<< std::endl;
std::getline(std::cin, currcard);
for (char c : currcard) {
if (isspace(c))
continue;
switch (c) {
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
++count;
break;
case '7':
case '8':
case '9':
break;
case 'A':
case 'J':
case 'Q':
case 'K':
--count;
break;
default:
//std::cout << "Invalid Entry\n";
break;
}
}
std::cout <<"Current count: "<< count << std::endl;
//user enter cards seen on table and if below 7 increment
//based on count the program returns if you should hit or quit
return 0;
}
Notice I have added a check for white spaces, and removed the message for invalid entries: both simply get ignored. But if needed that line can be uncommented.
Old solution
You can use cin.getline() as suggested in the comments, in conjunction with a flag that triggers exit from the loop once three inputs are given:
#include <iostream>
int main(){
static int count = 0, flag = 0;
char currcard;
std::cout << "Enter cards seen on table: "<< std::endl;
while(std::cin.getline(&currcard, 3)){
switch (currcard)
{
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
++count;
break;
case '7':
case '8':
case '9':
break;
case 'A':
case 'J':
case 'Q':
case 'K':
--count;
break;
default:
std::cout << "Invalid Entry\n";
--flag;
break;
}
++flag;
if (flag == 3)
break;
}
std::cout <<"Current count: "<< count << std::endl;
//user enter cards seen on table and if below 7 increment
//based on count the program returns if you should hit or quit
return 0;
}
There is also a flag decrement for invalid entries.
I'm in the middle of taking an online C++ course, and I've been having issues with this homework problem. I tried reaching out to my professor twice, but he hasn't responded. I've sought out many solutions, but since I'm new in the course, many of the solutions involve using techniques I haven't learned yet (like character arrays.) I can get the conversion program to work, but I want the program to allow to process as many user inputs as the user wants.
When I run the program, the program accepts my first input that is 'y' or 'Y' to run the program. It then will ask for a string to convert to the telephone number. This works. However, I need the program to ask the user if they want to run the program again to convert another string to a telephone number or to terminate the program.
I put in another cin at the end of the first while loop to prompt for another input, but it gets skipped over everytime and keeps doing the while loop.
Question: Why is the last prompt to repeat the program get skipped every time I've run it? What am I missing?
Here's the problem and what I've done so far:
Problem:
To make telephone numbers easier to remember, some companies use
letters to show their telephone number. For example, using letters,
the telephone number 438-5626 can be shown as GET LOAN.
In some cases, to make a telephone number meaningful, companies might
use more than seven letters. For example, 225-5466 can be displayed as
CALL HOME, which uses eight letters. Instructions
Write a program that prompts the user to enter a telephone number
expressed in letters and outputs the corresponding telephone number in
digits.
If the user enters more than seven letters, then process only the
first seven letters.
Also output the - (hyphen) after the third digit.
Allow the user to use both uppercase and lowercase letters as well as
spaces between words.
Moreover, your program should process as many telephone numbers as the
user wants.
My code so far:
#include <iostream>
using namespace std;
int main()
{
char letter, runLetter;
int counter = 0;
cout << "Enter Y/y to convert a telephone number from letters to digits"
<< endl;
cout << "Enter any other key to terminate the program." << endl;
cin >> runLetter;
while (runLetter == 'y' || runLetter == 'Y')
{
cout << "Enter in a telephone number as letters: " << endl;
while (cin.get(letter) && counter < 7 )
{
if (letter != ' ' && letter >= 'A' && letter <= 'z')
{
counter++;
if (letter > 'Z')
{
letter = (int)letter-32;
}
if (counter == 4)
cout << "-";
switch (letter)
{
case 'A':
case 'B':
case 'C':
{
cout << "2";
break;
}
case 'D':
case 'E':
case 'F':
{
cout << "3";
break;
}
case 'G':
case 'H':
case 'I':
{
cout << "4";
break;
}
case 'J':
case 'K':
case 'L':
{
cout << "5";
break;
}
case 'M':
case 'N':
case 'O':
{
cout << "6";
break;
}
case 'P':
case 'Q':
case 'R':
case 'S':
{
cout << "7";
break;
}
case 'T':
case 'U':
case 'V':
{
cout << "8";
break;
}
case 'W':
case 'X':
case 'Y':
case 'Z':
{
cout << "9";
break;
}
default:
break;
}
}
}
cout << endl;
cout << "To process another telephone number, enter Y/y" << endl;
cout << "Enter any other key to terminate the program." << endl;
cin >> runLetter;
}
cout << "Goodbye. " << endl;
return 0;
}
Thanks in advance for any help. I know this might be an easy solution, but I've been tinkering with this program for a couple of days now.
Tried moving the last user prompt in and out of each if/else structure and different while loops. Not sure what I can do to make the program take a new input after the first iteration.
A very good hint to your problem is the comment from #AlanBirtles. Also I know you are a beginner and you may not know about std::string but you should use it because you are learning C++ not C. in a nutshell, it is a C++ way of dealing with char arrays, also better than just that.
Here is your code with minimum changes to do what you are looking for. The main changes is the use of std::string, the use of std::getline and the definition of the counter inside the while loop.
#include <iostream>
#include <string>
using namespace std;
int main()
{
char letter;
std::string runLetter;
std::string number;
cout << "Enter Y/y to convert a telephone number from letters to digits"
<< endl;
cout << "Enter any other key to terminate the program." << endl;
std::getline( std::cin, runLetter);
while (runLetter == "y" || runLetter == "Y")
{
int counter = 0;
cout << "Enter in a telephone number as letters: " << endl;
std::getline(std::cin, number);
for (int i = 0; i < number.size(); i++)
{
letter = number[i];
if (counter < 7)
if (letter != ' ' && letter >= 'A' && letter <= 'z')
{
counter++;
if (letter > 'Z')
{
letter = (int)letter - 32;
}
if (counter == 4)
cout << "-";
switch (letter)
{
case 'A':
case 'B':
case 'C':
{
cout << "2";
break;
}
case 'D':
case 'E':
case 'F':
{
cout << "3";
break;
}
case 'G':
case 'H':
case 'I':
{
cout << "4";
break;
}
case 'J':
case 'K':
case 'L':
{
cout << "5";
break;
}
case 'M':
case 'N':
case 'O':
{
cout << "6";
break;
}
case 'P':
case 'Q':
case 'R':
case 'S':
{
cout << "7";
break;
}
case 'T':
case 'U':
case 'V':
{
cout << "8";
break;
}
case 'W':
case 'X':
case 'Y':
case 'Z':
{
cout << "9";
break;
}
default:
break;
}
}
}
cout << endl;
cout << "To process another telephone number, enter Y/y" << endl;
cout << "Enter any other key to terminate the program." << endl;
std::getline(std::cin, runLetter);
}
cout << "Goodbye. " << endl;
return 0;
}
I found the following errors in your code:
You do not reset the variable counter to 0 in the second loop iteration, so that counter has the value 7 in the entire second loop iteration, which causes the inner while loop not to be entered. This bug should be clearly visible when running your program line by line in a debugger while monitoring the values of all variables.
You always read exactly 7 characters from the user per loop iteration, which is wrong. You should always read exactly one line per loop iteration. In other words, you should read until you find the newline character. You can ignore every character after the 7th letter, but you must still consume them from the input stream, otherwise they will be read in the next loop iteration(s), which you do not want. However, this does not mean that you can simply ignore everything after the 7th character, because the number of characters is not necessarily identical to the number of letters. For example, if a 7 character string has one space character, then it only has 6 letters. As stated in the task description, the user should be allowed to enter spaces in the string.
This question already has answers here:
How do I select a range of values in a switch statement?
(18 answers)
Closed 2 years ago.
How does one accept more than one value for a single case in C++? I know you can make a range of values for one case (e.g. case 1..2) in some other languages, but it doesn't seem to be working in C++ on Xcode.
int main() {
int input;
cin >> input;
switch (input) {
case 1:
cout << "option 1 \n";
break;
case 2..3: //This is where the error occurs
cout << "option 2 and 3 \n";
break;
default:
break;
}
return 0;
}
The program shows an error saying "Invalid suffix '.3' on floating constant" where the range is.
You can "fall through" by having sequential case statements without a break between them.
switch (input) {
case 1:
cout << "option 1 \n";
break;
case 2:
case 3:
cout << "option 2 and 3 \n";
break;
default:
break;
}
Note that some compilers support range syntax like case 50 ... 100 but this is non-standard C++ and will likely not work on other compilers.
You could simply do:
switch (input) {
case 1:
cout << "option 1 \n";
break;
case 2: [[fallthrough]]
case 3:
cout << "option 2 and 3 \n";
break;
default:
break;
}
Note that case 2 ... 3 is called case ranges, and is a non-standard gcc extension that you could use.
You can't do a range of values, but you can do multiple values:
switch (input) {
case 1:
cout << "option 1 \n";
break;
case 2: case 3: case 4:
cout << "option 2 or 3 or 4\n";
break;
default:
break;
}
You need to use spaces between them with three(...)
int main() {
int input;
cin >> input;
switch (input) {
case 1:
cout << "option 1 \n";
break;
case 2 ... 3: //This is where the error occurs
cout << "option 2 and 3 \n";
break;
default:
break;
}
return 0;
}
new here, trying to figure out how to repeat my program. I need to understand how to insert a loop, i think a "do while" loop will work for this, but I am unsure because I have tried a few places of insertion and cannot get it to work right.
So my program is a telephone program, I am sure everyone here has done this in school, I am learning to do this and this is the part that I am confused on. My code is below.
I just need to make it possible for the user to keep entering phone numbers, over and over again.
I feel like I should be inserting a "do" before line14 "for (counter = 0...
Then insert the "while" portion at line 94 between the brackets. For some reason, that doesn't work for me and I am now stumped.
NOTE This is an assignment for school, so please explain to me rather than just show me. Thanks for everyones help.
#include <iostream>
using namespace std;
int main() {
int counter;
char phoneNumber;
cout << "\nEnter a phone number in letters only." << endl;
for (counter = 0; counter < 7; counter++)
{
cin >> phoneNumber;
if (counter == 3)
cout << "-";
if (phoneNumber >= 'A' && phoneNumber <= 'Z'
|| phoneNumber >= 'a' && phoneNumber <= 'z')
switch (phoneNumber)
{
case 'A':
case 'a':
case 'B':
case 'b':
case 'C':
case 'c':
cout << 2; // keypad starts with 2 for letters ABC, abc
break;
case 'D':
case 'd':
case 'E':
case 'e':
case 'F':
case 'f':
cout << 3; //for letter DEF, def
break;
case 'G':
case 'g':
case 'H':
case 'h':
case 'I':
case 'i':
cout << 4; //for letters GHI, ghi
break;
case 'J':
case 'j':
case 'K':
case 'k':
case 'L':
case 'l':
cout << 5; //for letter JKL, jkl
break;
case 'M':
case 'm':
case 'N':
case 'n':
case 'O':
case 'o':
cout << 6; //for letters MNO, mno
break;
case 'P':
case 'p':
case 'Q':
case 'q':
case 'R':
case 'r':
case 'S':
case 's':
cout << 7; //for letters PQRS, pqrs
break;
case 'T':
case 't':
case 'U':
case 'u':
case 'V':
case 'v':
cout << 8; //for letters TUV, tuv
break;
case 'W':
case 'w':
case 'X':
case 'x':
case 'Y':
case 'y':
case 'Z':
case 'z':
cout << 9; //for letters WXYZ, wxyz
break;
}
}
return 0;
}
As already said by pb772 an infinite loop of type
do { //Stuff you'd like to do } while(1);
would be fine, especially since it's a school assignment, but not ideal as always stated by pb772.
I've seen advises to cycle a finite number of times and then exit but I would instead do something like a special character like '#' or '!' that will trigger a condition to exit the loop. I would see this like an exit/escape character. In the end is up to you, if you want you can do anything and what I'm proposing is just an idea to inspire you. For example another idea would be, if you'd like to go deeper, wait for another input to define what action to perform, you trigger the "command console" with '!' and then type 'q' to exit or also read the characters into a string at first so you could do complex "commands" like "!q".
Here's the simple version:
bool loop_condition = true;
do
{
if(input == '!')
{
loop_condition = false;
}
else
{
//Stuff you'd like to do if the read character is not !
}while(loop_condition == true);
Just to provide context here is what's happening:
I declare a variable named loop_condition
Inside the loop I check if the typed character is !
If so set the variable loop_condition to false with subsequent exit from the loop
Else just execute your code and loop
As I already said this is a very simple example just to give you an idea and can be improved a lot.
I suggest wrapping the for (counter=0... loop with a while (!cin.eof()) { block. This will allow the user to continue to enter in characters, until an EOF character (e.g. ctrl-D).
You may find you want to output a newline after every 7th character, to make the display look nice.
do {
//your code here;
} while (1);
This will repeatly infinitely which is not a good practice.
int number_of_phones = 10; // total number of phones you want
int i = 0;
do {
//your code here;
i=i+1;
} while (i<number_of_phones);
This will make it run 10 times for example
You can have whatever condition you want in a for loop, including nothing at all, which is treated as true.
for(;;) {
// code
}
is the same as
while (true) {
// code
}
is the same as
do {
// code
} while (true)
It sounds like you mixed up the placement of braces when you tried do { ... } while (true). You may want to move your big switch into a function, so that it's more obvious what scope a partiular } ends.
#include <iostream>
int phone_key(char key)
{
switch (key)
{
case 'A':
case 'a':
case 'B':
case 'b':
case 'C':
case 'c':
return 2;
case 'D':
case 'd':
case 'E':
case 'e':
case 'F':
case 'f':
return 3;
case 'G':
case 'g':
case 'H':
case 'h':
case 'I':
case 'i':
return 4;
case 'J':
case 'j':
case 'K':
case 'k':
case 'L':
case 'l':
return 5;
case 'M':
case 'm':
case 'N':
case 'n':
case 'O':
case 'o':
return 6;
case 'P':
case 'p':
case 'Q':
case 'q':
case 'R':
case 'r':
case 'S':
case 's':
return 7;
case 'T':
case 't':
case 'U':
case 'u':
case 'V':
case 'v':
return 8;
case 'W':
case 'w':
case 'X':
case 'x':
case 'Y':
case 'y':
case 'Z':
case 'z':
return 9;
}
return 0;
}
int main() {
for (;;)
{
std::cout << "\nEnter a phone number in letters only." << std::endl;
for (int counter = 0; counter < 7; counter++)
{
char phoneNumber;
cin >> phoneNumber;
if (counter == 3)
std::cout << "-";
std::cout << phone_key(phoneNumber);
}
}
}
Why does this code always return 'false' and activates the goto even when I type a digit? Can anyone please help me? Thank you!
char userValue = '4';
auto h = true;
tryAgain:
std::cout << "Please type a digit: ";
std::cin >> userValue;
switch (userValue) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
h = true;
default:
h = false;
}
switch (h) {
case true:
std::cout << "This character is a digit.";
case false:
std::cout << "Wrong! Try again!" << std::endl;
goto tryAgain;
}
You simply forgot to break out of the case if it has been processed.
That way it will fall through the cases and handle the false case after the true case has been handled.
switch (h) {
case true:
std::cout << "This character is a digit.";
break;
case false:
std::cout << "Wrong! Try again!" << std::endl;
goto tryAgain;
//not necessarily needed because goto leaves the scope anyway.
//break;
}
The same issue here, break if you wan't to stop the fallthrough:
switch (userValue) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
h = true;
break;
default:
h = false;
break;
}