Please help me figure out why my code is not working properly.I had thought my logic was sound but later found it will run one time through fine however if the user opts to enter another value it will always be returned as an error.
#include <iomanip>
#include <iostream>
#include <cstdlib>
using namespace std;
int const TRUE = 1;
int const FALSE = 0;
// declares functions
void GetZipcode();
void RunAgain();
int GetSum(char d1, char d2, char d3, char d4, char d5);
int GetCheckDigitValue(int sum);
string GetDigitCode(char digit);
int main (){
// calls function
GetZipcode();
return(0);
}
void GetZipcode(){
// declares values
char d1;
char d2;
char d3;
char d4;
char d5;
//gather data at once but reads in each value
cout << "Enter a zipcode: " ;
cin.get(d1);
cin.get(d2);
cin.get(d3);
cin.get(d4);
cin.get(d5);
cin.ignore(200, '\n');
//checks to make sure the data is only digits if not usable prints error message
if (isdigit(d1) && isdigit(d2) && isdigit(d3) && isdigit(d4) && isdigit(d5)){
//prints barcode if zipcode entered is valid
cout <<" | " << GetDigitCode(d1) << GetDigitCode(d2) << GetDigitCode(d3) << GetDigitCode(d4) << GetDigitCode(d5) << GetDigitCode(GetCheckDigitValue(GetSum(d1,d2,d3,d4,d5))+'0') << " | " << endl;
//calls function to ask to run program again
RunAgain();
//prints error message and calls function to ask to run again
} else {
cout << "Error, zipcode must be 5 digits and contain no special characters" << endl;
RunAgain();
}
}
// run program again function
void RunAgain(){
char answer;
cout << " Continue (y/n)?";
cin >> answer;
if ( answer == 'y' || answer == 'Y'){
GetZipcode();
}
}
//gets sum of zip for later use
int GetSum(char d1, char d2, char d3, char d4, char d5){
int sum = 0;
sum = (d1 - '0') + (d2 - '0') + (d3 - '0') + (d4 - '0') + (d5 - '0');
return sum;
}
//uses sum to find check digit value
int GetCheckDigitValue(int sum){
int x = 0;
do {
x++;
} while(((sum + x) % 10 == 0) != 1);
return x;
}
// converts each digit to barcode value
string GetDigitCode(char digit){
if (digit == '0'){ return "||:::"; }
else if (digit == '1'){ return ":::||"; }
else if (digit == '2'){ return "::|:|"; }
else if (digit == '3'){ return "::||:"; }
else if (digit == '4'){ return ":|::|"; }
else if (digit == '5'){ return ":|:|:"; }
else if (digit == '6'){ return ":||::"; }
else if (digit == '7'){ return "|:::|"; }
else if (digit == '8'){ return "::|:|"; }
else if (digit == '9'){ return "|:|::"; }
}
I went through your code. Your logic is also sound and you've written it in nice way.
I want to solve the query for you.
So, let's start by examining the program flow.
Inside main() method, you are calling GetZipcode() method.
Inside GetZipcode() method, you're declaring 5 character variables and saving the zipcode in it.
Here, you've mentioned the line cin.ignore(200, '\n');
It is very important and it will be useful for you in many programs.
Now, after this, you've checked whether all 5 characters received from the input are digits or not. If yes, then you've printed the digit codes and asks user to run the program again. If user says yes, then again it will call GetZipcode() method and the same process will continue.
If any one of all 5 inputs is not valid then you've shown error message.
This is the complete flow of the program.
Now, as you're saying, the program is able to print the output correctly in the first run. When user type 'y' or 'Y' and again enter new zipcode, after that it gives error. So, let's see what is happening here.
To let you understand it in a better way, I have executed the current code with the same scenario. Here, I have added 5 lines in your code to display the inputs received by the program in the output window.
The lines are:
cout << endl <<
d1;
cout << endl << d2;
cout << endl << d3;
cout << endl << d4;
cout << endl << d5 << endl;
And I added them after the line cin.ignore(200, '\n'); in GetZipCode() method.
[ Note: These are just to show you the problem only. These lines are only for debugging they won't get added in the final code so I am not uploading the whole code again. ]
Now, when I run the program after adding these 5 lines, see the sample output:

I entered a zipcode 12345 and pressed ENTER key so the program will start printing from the next line.
After getting the input, I have printed them as cout << endl << d1; so it first leaves 1 line(because of endl) and then prints first digit i.e. character received.
As this is the first run, we can see d1 to d5 values are 1, 2, 3, 4 and 5 respectively and it also generates the code.
Now, after the code is printed, user is asked to run again or not.
I pressed 'y' and an ENTER key.
Now, remember that ENTER or RETURN Key represent a new line character \n that can also be stored inside a character variable.
Here, you stored this 'y' inside answer variable, but what about the next character '\n'.
It is not assigned to any variable yet in the current code so it is still present in our input stream and it is the only entry because all the earlier characters were stored in some variable so input stream did not store them.
So, right now the input stream is : '\n'.
After this, as I wrote 'y' then GetZipCode() method will again be called and again user is supposed to enter 5 digits.
In the next run, I entered 45678. These characters got stored inside the input stream. As input stream already had 1 character, new input stream became : '\n', '4', '5', '6', '7' and '8'.
So, when the statement cin.get(d1); will be executed, it wiill be given the next available character from the stream which is '\n'. Ater that d2 will be given '4' and so on.
So, as you can see, d1 = '\n' so when the values are printed, it leaves 1 more line than previous run and then prints 4, 5, 6 and 7. Here, 1 more line is actually the content of 'd1' which is a new line character so 1 more line is left.
Now, as '\n' is not a digit, inside the if() condition, isdigit(d1) will return false and so it will go to the else part and print the error.
Similarly, in the next RunAgain() calll, if I again press 'y' and ENTER key, then again my input stream will have a character '\n' as earlier and this will keep on giving error till you press 'y' followed by ENTER key.
So, an ENTER or RETURN key (that represents a new line character '\n') pressed after 'y' or 'Y' is the cause of this problem.
Now, how to solve this issue? Actually, in your code, you've used it at one place. In the beginning of the answer, I had highlighted one line which was:
cin.ignore(200, '\n');
Conceptually this statement says that, inside input stream 'cin', ignore the next 200 characters i.e. don't save them in the stream. But, if there's a '\n' character found in between somewhere before 200 characters, then stop discarding the next letters and immediately save the next letters.
Here I believe you've used it to ignore the '\n' character only as your input is never going to be 200 characters long so you wish to tell the compiler that in between the input, if '\n' is found then ignore till that placce and again start storing the inputs.
So, in simple terms, here the purpose of this line was to ignore i.e. handle a '\n' character.
So, let's use the same to solve our current problem.
Where it should be typed?
See your current code, where did you type the line cin.ignore(200, '\n'); ?
You typed it after you stored your desired inputs in the variables.
So, again we'll do the same.
We'll write cin.ignore(200, '\n'); after we store the required variable.
Here, 'y' or 'n' or an input is getting stored in 'answer' variable so after we have got some value inside the 'answer' and before we process an if() condition, we will copy this line inside RunAgain() method.
So, the modified RunAgain() method will be:
void RunAgain()
{
char answer;
cout << " Continue (y/n)?";
cin >> answer;
cin.ignore(200, '\n');
if ( answer == 'y' || answer
== 'Y')
{
GetZipcode();
}
}
This says that first get some input in 'answer', then ignore (till 200 characters and stop ignoring when found) '\n' and again store next values inside the stream.
So, here we handled a '\n' that we were entering after 'y' by pressing an ENTER key.
Now, with this modification, and by removing those 5 lines that I inserted for debugging only, when I run the program, I got the following output:

So, as you can see, after handling the '\n', we are able to run the program for more than once by pressing 'y'.
All we did here is, just added 1 line inside RunAgain() method to handle a new line character that is generated when pressed ENTER or RETURN key.
So, this is how the problem can be solved.
I tried to give the answer in detail and along with some debugging information so that you can understand it in bettere way.
Go through this and if there's any query then surely comment about it.
I will address it and try to resolve it.
Thank you. :)
Please help me figure out why my code is not working properly.I had thought my logic...
i am having issues correcting an error in my program here is my code: #include <iostream> // define libraries #include <fstream> using namespace std; // Variable definitions: ifstream infp; // file handler enum Tokens {INT_LIT, IDENT, ASSIGN_OP, ADD_OP, SUB_OP, MUL_OP, DIV_OP, LEFT_PAREN, RIGHT_PAREN, LETTER, DIGIT, UNKNOWN,ENDFILE}; Tokens nextToken; // nextToken read from the file. int charClass; // char class char lexeme [100]; // number of characters per line char nextChar; // next char read from the file int lexLen; //...
Can some help me with my code I'm not sure why its not working. Thanks In this exercise, you are to modify the Classify Numbers programming example in this chapter. As written, the program inputs the data from the standard input device (keyboard) and outputs the results on the standard output device (screen). The program can process only 20 numbers. Rewrite the program to incorporate the following requirements: a. Data to the program is input from a file of an...
Code in C++: Please help me fix the error in function: void write_account(); //function to write record in binary file (NOTE: I able to store data to a txt file but however the data get error when I try to add on data the second time) void display_all(); //function to display all account details (NOTE: This function is to display all the info that save account.txt which is ID, Name, and Type) void modify_account(int); //function to modify record of file...
C++ problem where should I do overflow part? in this code do not write a new code for me please /////////////////// // this program read two number from the user // and display the sum of the number #include <iostream> #include <string> using namespace std; const int MAX_DIGITS = 10; //10 digits void input_number(char num[MAX_DIGITS]); void output_number(char num[MAX_DIGITS]); void add(char num1[MAX_DIGITS], char num2[MAX_DIGITS], char result[MAX_DIGITS], int &base); int main() { // declare the array = {'0'} char num1[MAX_DIGITS] ={'0'}; char...
rewrite this c code in python #include <iostream> using std::cout; using std::cin; using std::endl; int charClass; char lexeme[100]; char str[200]; char nextChar; const int LETTER = 0; const int DIGIT = 1; const int UNKNOWN = -1; const int OPAREN = 2; const int CPAREN = 3; const int PLUS = 4; const int MINUS = 5; const int MUL = 6; const int DIV = 7; const int ID_CODE = 100; const int PLUS_CODE = 101; const int MINUS_CODE...
modify the program pls so it then asks the user for another input making the program ask for a yes or no question looping it codeblocks #include <stdio.h> #include <ctype.h> #define NEWLINE '\n' int main(void) { /* Declare variables and function prototypes. */ int k=0, formula[20], n, current=0, done=0, d1, d2; double error=0, weight, total=0; double atomic_wt(int atom); /* Read chemical formula from keyboard. */ printf("Enter chemical formula for amino acid: \n"); while ((formula[k]=getchar()) != NEWLINE) k++; n = k; ...
Hello, please correct the following C++ CODE it is not working on visual studio: (I WILL RATE, NO INCOMPLETE OR WRONG SOLUTIONS PLEASE) // CPP program to evaluate a given // expression where tokens are // separated by space. #include using namespace std; // Function to find precedence of // operators. int precedence(char op){ if(op == '+'||op == '-') return 1; if(op == '*'||op == '/') return 2; return 0; } // Function to perform arithmetic operations. int applyOp(int a,...
can someone please double check my code here are the requirements please help me fulfill the requirements Using the material in the textbook (NumberList) as a sample, design your own dynamic linked list class (using pointers) to hold a series of capital letters. The class should have the following member functions: append, insert (at a specific position, return -1 if that position doesn't exist), delete (at a specific position, return -1 if that position doesn't exist), print, reverse (which rearranges...
C++ NEED HELP WITH MY REVERSE STRING FUNCTION IN LINK LIST A function Reverse, that traverses the linked list and prints the reverse text to the standard output, without changing the linked list. ( Pass the linked list by value, you have the freedom to create a doubly linked list that is a copy of the original list in your program before you call the function) #include "pch.h" #include <iostream> #include <string.h> #include <string> using namespace std; #define MAX 512...
In C++ please!
*Do not use any other library functions(like strlen) than the
one posted(<cstddef>) in the code below!*
/**
CS 150 C-Strings
Follow the instructions on your handout to complete the
requested function. You may not use ANY library functions
or include any headers, except for <cstddef> for
size_t.
*/
#include <cstddef> // size_t for sizes and indexes
///////////////// WRITE YOUR FUNCTION BELOW THIS LINE
///////////////////////
///////////////// WRITE YOUR FUNCTION ABOVE THIS LINE
///////////////////////
// These are OK after...