expected '}' at end of input in my program main function - c++

This program is supposed to teach functions. I have separated the functions each into header files. I think there is a curly brace somewhere that is backwards or missing, but I have stared at this program for hours and tried re-arranging things and can't seem to get anything going.
This program is supposed to read a phone number and print it out. If it is provided letters then it will sort it to a number 0-9 like on a phone keypad, after making it an uppercase letter. It will also return error codes for invalid characters, etc., which is controlled by a switch statement.
Main function
One of the errors I am getting is on the closing brace on the last line:
expected '}' at end of input
#include <iostream>
#include <cctype>
#include "Read_Dials.h"
#include "To_Digit.h"
#include "Acknowledge_Call.h"
using namespace std;
int main()
{
char digit1, digit2, digit3, digit4, digit5, digit6, digit7, digit8;
int return_value = 0;
return_value = int Read_dials(digit1, digit2, digit3, digit4, digit5, digit6, digit7, digit8);
if (return_value != -5)
break;
switch(return_value){
case -1:
cout << "ERROR - An invalid character was entered. Please try again, only numbers or letters this time." << endl;
break;
case -2:
cout << "ERROR - Phone number cant start with 0." << endl;
break;
case -3:
cout << "ERROR - This isn't the movies, Phone numbers dont start with \" 555 \" here buddy :/" << endl;
break;
case -4:
cout << "ERROR - Please make sure the hyphen is in position 4." << endl;
break;
default:
void Acknowledge_Call(digit1, digit2, digit3, digit4, digit5, digit6, digit7, digit8);
}
return 0;
}
Read_Dials Function
No errors in this function
int Read_Dials(char &num1, char &num2, char &num3, char &num4, char &num5, char &num6, char &num7, char &num8)
{
#include "To_Digit.h"
int i = 0;
do{
i++;
cout << "Please enter the character for position #" << i << " in the phone number\n";
cout << "NOTE: Please put the hyphen \" - \" in the fourth position and use \"Q\"to quit." << endl;
char temp;
cin >>temp;
if (i = 1 && temp == 0)
{
return_value = -2;
}
else if (i == 1 && (temp == 'q' || temp == 'Q'))
{
return_value -5;
}
else if (i == 1)
{
temp = &num1;
&inputValue = &num1;
int To_Digit(char &num1);
}
else if (i == 2)
{
temp = &num2;
&inputValue = &num2;
int To_Digit(char &num2);
}
else if (i == 3)
{
temp = &num3;
&inputValue = &num3;
int To_Digit(char &num3);
}
else if (&num1 == '5' && &num2 == '5' && &num3 == '5')
{
return_value -3;
}
else if (i == 4 && temp != '-')
{
return_value -4;
}
else if (i == 5)
{
temp = &num5;
&inputValue = &num5;
int To_Digit(char &num5);
}
else if (i == 6)
{
temp = &num6;
&inputValue = &num6;
int To_Digit(char &num6);
}
else if (i == 7)
{
temp = &num7;
&inputValue = &num7;
int To_Digit(char &num7);
}
else if (i == 8)
{
temp = &num8;
&inputValue = &num8;
int To_Digit(char &num8);
}
}while (i < 8)
return 0;
}
To_Digit Function
The second and final error I'm getting is here, on the second line (the opening brace):
A function-definition is not allowed here before '{' token
int To_Digit(char &inputValue)
{
char &inputValue;
if (isdigit(&inputValue))
break;
&inputValue = toupper(&inputValue);
switch(&inputValue){
case 'A': case 'B': case 'C':
&inputValue = '2';
break;
case 'D': case 'E': case 'F':
&inputValue = '3';
break;
case 'G': case 'H': case 'I':
&inputValue = '4';
break;
case 'J': case 'K': case 'L':
&inputValue = '5';
break;
case 'M': case 'N': case 'O':
&inputValue = '6';
break;
case 'P': case 'Q': case 'R': case 'S':
&inputValue = '7';
break;
case 'T': case 'U': case 'V':
&inputValue = '8';
break;
case 'W': case 'X': case 'Y': case 'Z':
&inputValue = '9';
break;
default:
return -1;
}
}
Acknowledge_Call function
No errors with this function.
void Acknowledge_Call(digit1, digit2, digit3, digit4, digit5, digit6, digit7, digit8)
{
cout << "Phone number entered is: " << digit1 << digit2 << digit3 << digit4 << digit5 << digit6 << digit7 << digit8 << endl;
}
What's wrong with this code? How can I fix it?

I haven't tried to run the code myself just yet, but the only thing I can see that looks hokey to me is in the "Read_Dials" function... don't put a #INCLUDE statement within a function. Always place those statements at the top of the file.
Move the #include and let us know what that does.
Good luck.

default:
void Acknowledge_Call(digit1, digit2, digit3, digit4, digit5, digit6, digit7, digit8);
Return type is not used while calling a function. So, drop void. Also default case should have a break, else it will fall-through.
int Read_Dials(char &num1, char &num2, char &num3, char &num4, char &num5, char &num6, char &num7, char &num8)
{
#include "To_Digit.h" // The header actually has a definition. Preprocessor
// copies the content of To_Digit.h here. So, you have
// a function definition inside another function while
// compilation phase which is not allowed. So remove
// it and place it at top of the file.
// .....
}

Your #includes should be at the top of the file...
if (return_value != -5)
break;
(in main) is not allowed as there is no loop for it to break out of

Here are some issues (besides the fact you didn't supply header files):
Function declaration after "default" in main()
Remove the void in front of the function call.
Types for parameters not specified in declaration for Acknowledge_Call
Change to:
void Acknowledge_Call(char digit1, char digit2, char digit3, char digit4, char digit5, char digit6, char digit7, char digit8)
Remove the int in front of Read_dials in the main function.
In main(), change 'Read_dialstoRead_Dials:
The C++ language is case-sensitive, thus 'dials != Dials != dIaLs.
Remove break from after if in main() function:
You want return 1; or return EXIT_FAILURE; or exit(1);
Remember to add these lines to Acknowledge_Calls.cpp:
#include "acknowledge_call.h"
#include <iostream>
using namespace std;
Remember to add these lines to Read_Dials.cpp:
#include "read_dials.h"
#include <iostream>
using namespace std;
In Read_Dials.cpp, move the #include "To_Digit.h to the top of the file.
When executing a function all, do not put the return type nor the parameter types in the call.
For example, use:
num1 = To_Digit(digit1);
instead of
int To_Digit(char &num1);
You need to have a long talk with your instructor about how to call functions and pass parameters (this time, listen carefully). Also, read a good book on C++.

Related

My code works for C++ but not when converted to C language

I am providing the code that I converted to the C language and the converted code as well. The code works just as desired in C++ but I am unable to enter the value of the 'Operator' variable in the C language version.
This is the C++ code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
float num;
float num2;
char Operator;
char choice;
float result;
cout << "Select one of the following items:\n";
cout << "B) - Binary Mathematical Operations, such as addition and subtraction.\n";
cout << "U) - Unary Mathematical Operations, such as square root, and log.\n";
cout << "A) - Advances Mathematical Operations, using variables, arrays.\n";
cout << "V) – Define variables and assign them values.\n";
cout << "E) - Exit\n";
cin >> choice;
if (choice == 'U' || choice == 'u') {
cout << "Please enter the operation ( S (for square root) , L (for logarithm) , E (for exponential) , C (for ceil) , F (for floor) ):\n";
cin >> Operator;
rerun:
cout << "Enter a positive value.\n";
cin >> num;
if (num < 0) {
goto rerun;
}
else {
switch (Operator) {
case 'S':
result = sqrt(num);
break;
case 'L':
result = log(num);
break;
case 'E':
result = exp(num);
break;
case 'C':
result = ceil(num);
break;
case 'F':
result = floor(num);
break;
default:
result = 0;
break;
}
}
cout << fixed << setprecision(2) << result;
}
return 0;
}
This is the C language code:
#include <stdio.h>
#include <math.h>
int main()
{
double num;
char Operator;
char choice;
double result;
printf("Select one of the following items:\n");
printf("B) - Binary Mathematical Operations, such as addition and subtraction.\n");
printf("U) - Unary Mathematical Operations, such as square root, and log.\n");
printf("A) - Advances Mathematical Operations, using variables, arrays.\n");
printf("V) - Define variables and assign them values.\n");
printf("E) - Exit\n");
scanf("%c", &choice);
if (choice == 'U' || choice == 'u') {
printf("Please enter the operation ( S (for square root) , L (for logarithm) , E (for exponential) , C (for ceil) , F (for floor) ):\n");
scanf("%c", &Operator);
printf("Enter a positive value.\n");
scanf("%lf", &num);
switch (Operator) {
case 'S':
result = sqrt(num);
break;
case 'L':
result = log(num);
break;
case 'E':
result = exp(num);
break;
case 'C':
result = ceil(num);
break;
case 'F':
result = floor(num);
break;
default:
result = 0;
break;
}
printf("the answer is %lf", result);
}
return 0;
}
Both the codes are working except I am unable to input the value of the 'Operator' variable in the C version whereas it works great in C++.
Any help regarding this is truly appreciated.
Unlike the equivalent C++ code inputing a character using %c does not skip whitespace. To do that you should add a space before the %c, like this
scanf(" %c",&Operator); // skip whitespace then read a char
This code will work for you!.
Actually you should have better understanding of how buffered input works.
#include <stdio.h>
#include <math.h>
int main()
{
double num;
char Operator;
char choice;
double result;
printf("Select one of the following items:\n");
printf("B) - Binary Mathematical Operations, such as addition and subtraction.\n");
printf("U) - Unary Mathematical Operations, such as square root, and log.\n");
printf("A) - Advances Mathematical Operations, using variables, arrays.\n");
printf("V) - Define variables and assign them values.\n");
printf("E) - Exit\n");
scanf("%c", &choice);
char eat_line;
scanf("%c", &eat_line);
if (choice == 'U' || choice == 'u') {
printf("Please enter the operation ( S (for square root) , L (for logarithm) , E (for exponential) , C (for ceil) , F (for floor) ):\n");
scanf("%c", &Operator);
scanf("%c", &eat_line);
printf("Enter a positive value.\n");
scanf("%lf", &num);
switch (Operator) {
case 'S':
result = sqrt(num);
break;
case 'L':
result = log(num);
break;
case 'E':
result = exp(num);
break;
case 'C':
result = ceil(num);
break;
case 'F':
result = floor(num);
break;
default:
result = 0;
break;
}
printf("the answer is %lf", result);
}
return 0;
}

c++ While Loop termination with function

scratching my head on this as it was working just fine earlier but when I went to add some other functions suddenly my program freaked out and I can not get it back to what it was.
class has me writing a rock/paper/scissors program to go up against a computer, any help with why the loop keeps terminating itself would be wonderful
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void RPSout(char);
int RPScomp();
int main() {
char choice;
int endit=0;
while (endit == 0)
{
cout << "\n\n\tReady to play Rock/Paper/Scissors against the computer??(please choose R/P/S)(Q to quit)\n";
cin >> choice;
RPSout(choice);
if (choice=='Q'||'q')
{endit=1;}
}
return 0;
}
void RPSout(char choose)
{
int RPS =0;
int comp=0;
switch (choose)
{
case 'R':
case 'r':
{
cout <<"Your choice: Rock";
break;
}
case 'P':
case 'p':
{
cout <<"Your choice: Paper";
break;
}
case 'S':
case 's':
{
cout << "Your choice: Scissors";
break;
}
case 'Q':
case 'q':
{
cout << "Bye Bye Bye";
break;
}
default:
cout<<"You enter nothing!"<<endl;
cout << "The valid choices are R/P/S/Q)";
}
return;
}
int RPScomp()
{
int comp=0;
const int MIN_VALUE =1;
const int MAX_VALUE =3;
unsigned seed = time(0);
srand(seed);
comp =(rand() % (MAX_VALUE - MIN_VALUE +1)) + MIN_VALUE;
return comp;
}
if (choice=='Q'||'q')
This is equivalent to
if ((choice == 'Q') || 'q')
Which is almost certainly not what you want. 'q' is a non-zero char literal, which is "truthy" and so this expression will never be false. It's akin to writing if (choice == 'Q' || true).
The solution is:
if (choice=='Q' || choice=='q')
The statement
if (choice=='Q'||'q')
always tests true and therefore sets your flag to terminate the loop.
Try:
if (choice=='Q'||choice=='q')
I think your if statement should be if (choice=='Q'|| choice=='q')
Your issue if with the if statement
if (choice=='Q'||'q')
{endit=1;}
the || 'q' part will always be true since 'q' in ASCII is not 0
Change your code to
if (choice=='Q'|| choice=='q')
{endit=1;}

A few coding convention/standard practice questions

I have this function that takes a string from main. The string contains all of the valid characters that a user can input from some menu options. Function will put character input into a variable and be compared to each character of the string. Compare input variable to the string characters until valid input is entered.
My question is, what is the best way to implement this loop? I don't like using while (true) with a return in the middle because it looks like an infinite loop with an exception in the middle, which makes it slightly harder to read, but I'm not sure how else I can do what I want it to do. What's the best practice for achieving my goal? Thanks.
char getValidKey(string validKeys)
{
char letter;
while (true) {
cout << "Operation ? ";
cin >> letter;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int i = 0; i < validKeys.length(); i++) {
if (letter == validKeys[i])
return letter;
}
cout << "Error. Invalid input.\n";
}
}
Also, I have a switch statement with multiple returns. Is it more common/preferred to assign calculations to a variable and have one return at the end or is this way generally okay?
string opStr;
switch (myOperation) {
case 1:
opStr = "RIGHT";
break;
case 2:
opStr = "LEFT";
break;
case 3:
opStr = "CENTER_ONLY";
break;
case 4:
opStr = "CENTER_MISSING";
break;
default:
opStr = "Error. Invalid input.";
break;
}
return opStr;
OR
switch (myOperation) {
case 1:
return "RIGHT";
break;
case 2:
return "LEFT";
break;
case 3:
return "CENTER_ONLY";
break;
case 4:
return "CENTER_MISSING";
break;
default:
return "Error. Invalid input.";
break;
}
For the first case, refactor your code in smaller self-contained functions, and it becomes clear to understand the logic of getValidKey even from a while(true):
char isKeyValid(char x, const string& validKeys)
{
return validKeys.find(x) != string::npos;
}
char readCharFromCin()
{
char letter;
cout << "Operation ? ";
cin >> letter;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return letter;
}
char getValidKey(const string& validKeys)
{
while (true)
{
const char key = readCharFromCin();
if(isKeyValid(key, validKeys)) return letter;
cout << "Error. Invalid input.\n";
}
}
For the second case, avoid break and simply return from your switch. Make the function containing the switch only do one thing.
string switchOperation(int myOperation)
{
switch (myOperation)
{
case 1: return "RIGHT";
case 2: return "LEFT";
case 3: return "CENTER_ONLY";
case 4: return "CENTER_MISSING";
}
return "Error. Invalid input.";
}
Also, try to maximize usage of const and pass string instances you're only reading by const& to avoid unnecessary copies.

C++ switch statement odd output

I'm working on a final assignment for an Intro to C++ course. What I've coded so far works, but it's producing some interesting output that I'm looking for clarification on. Here's my code:
(Caveat: Yes, I know using void main() sucks, but we're using Visual Studio in class, and this is the instructors preference.)
#include <string>
#include <iostream>
using namespace std;
void conversion(int);
void main()
{
int decimal_number, answer;
cout << "Please enter a whole decimal number (e.g. 20): ";
cin >> decimal_number;
if (decimal_number == 0)
{
answer = 0;
cout << "The hexadecimal value of your number is: " << answer;
getchar();
getchar();
}
else if (decimal_number < 0)
{
cout << "INVALID ENTRY" ;
getchar();
getchar();
}
else if (decimal_number > 0)
{
conversion(decimal_number);
}
getchar();
getchar();
}
void conversion (int decimal_number)
{
int count = 0, remainder, reverse_order;
char hexadecimal_number[10] = { NULL };
while (decimal_number != 0)
{
remainder = decimal_number % 16;
switch (remainder)
{
case 0:
hexadecimal_number[count] = '0';
count++;
break;
case 1:
hexadecimal_number[count] = '1';
count++;
break;
case 2:
hexadecimal_number[count] = '2';
count++;
break;
case 3:
hexadecimal_number[count] = '3';
count++;
break;
case 4:
hexadecimal_number[count] = '4';
count++;
break;
case 5:
hexadecimal_number[count] = '5';
count++;
break;
case 6:
hexadecimal_number[count] = '6';
count++;
break;
case 7:
hexadecimal_number[count] = '7';
count++;
break;
case 8:
hexadecimal_number[count] = '8';
count++;
break;
case 9:
hexadecimal_number[count] = '9';
count++;
break;
case 10:
hexadecimal_number[count] = 'A';
count++;
break;
case 11:
hexadecimal_number[count] = 'B';
count++;
break;
case 12:
hexadecimal_number[count] = 'C';
count++;
break;
case 13:
hexadecimal_number[count] = 'D';
count++;
break;
case 14:
hexadecimal_number[count] = 'E';
count++;
break;
case 15:
hexadecimal_number[count] = 'F';
count++;
break;
default:
cout << decimal_number << "+++ " << hexadecimal_number;
cout << "INVALID ENTRY";
getchar();
getchar();
}
decimal_number = decimal_number / 16;
}
cout << "The hexadecimal value of your number is: ";
for (reverse_order = count -1; reverse_order >= 0; reverse_order--)
{
cout << hexadecimal_number[reverse_order];
}
getchar();
getchar();
}
So, like I said: my code works. I can take any number input as a decimal, and convert it to its hexadecimal equivalent. However, I've found that I've had to include an IF statement within the main function of the code, because if the user inputs anything other than a decimal number into the decimal_number variable, the program will store a string of decimal numbers, into decimal_number, and I have no idea where those numbers come from. They don't appear to be the ASCII equivalents of anything.
... If none of this makes any sense, I'm sorry. just input cout << decimal_number after the line cin >> decimal_number, then run the code and see what weird number comes out. I hope that makes things clearer.
Anyway, my instructors stumped, and I'm stumped. I've got the above workaround in place that the instructor will accept, but for my own sanity, I just want to figure out what's going on. Any help or pointers is appreciated. Cheers!
You can test whether the result of cin >> decimal_number succeeded, like
if(!(cin>>decimal_number))
throw std::runtime_error("Oops, not a decimal number!");
This is a bit too extreme, you can also validate the input:
while(!(cin>>decimal_number))
{
std::cout << "Not decimal, input again ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
If you're not performing this kind of validation, then you leave the stream in an invalid state whenever reading a non-decimal, and the variable you think you're reading into will end up un-initialized.
However, I've found that I've had to include an IF statement within the main function of the code, because if the user inputs anything other than a decimal number into the decimal_number variable, the program will store a string of decimal numbers, into decimal_number, and I have no idea where those numbers come from.
Well, you did not initialise decimal_number to anything, and you do not have any error checking around the cin >> decimal_number call. So I'm not sure what else you expected but an unspecified value for decimal_number!
Your instructor should know this. It's worrying that, on top of teaching you to write code that is ill-formed per the International Standard (void main!!), they failed to discover this problem or note that you have no error checking.
What's the point of the assignment?
The conversion can be simplified to:
cout << hex << decimal_value << endl;
Or if you need it in a string:
std::string convert_decimal_to_hex_string(int decimal_value)
{
std::ostringstream output;
output << hex << value;
return output.str();
}
I believe the class should show you how to use std::string and existing language features (such as the hex manipulator). Using char for a string is dangerous.
Also, since you don't know the size or limit of the decimal values, you will need to dynamically allocate (i.e. during run-time) the array holding the characters. Think about allocating 2 characters and entering the value 1024; buffer overflow.
Change your program to use std::string. Refrain from character (C-Style) arrays.

Switch statement behavior in C++

I'm having trouble understanding my C++ switch statement.
I have to enter the accepted integer interval twice for the function to return to the switch. And then it falls straight through to case 2.
Inherited Class:
class Fugl : public DyrLuft
{
private:
int alder;
public:
Fugl() : DyrLuft()
{ }
void les()
{
do
{
cout << "\nSkriv inn fuglens alder: ";
cin >> alder;
if(alder < 0 || alder > 130)
cout << "\nDenne alderen virket usannsynlig, prøv igjen!\n";
} while(alder < 0 || alder > 130);
}
};
Main:
int main()
{
char valg = '\q';
cout << "Hvilken dyreart ønsker du å registrere? (Q for å avslutte)"
<< "\n1) - Fugl \n2) - Fisk \n3) - Insekt \n4) - Skalldyr\n";
do
{
cin >> valg;
switch(valg)
{
case '1':
{
Fugl fugl; fugl.les();
} break;
case '2':
{
Fisk fisk; fisk.les();
} break;
case '3':
{
Insekt insekt; insekt.les();
} break;
case '4':
{
Skalldyr skalldyr; skalldyr.les();
} break;
case 'Q': return 0;
case 'q': return 0;
default: cout << "Velg en av ovennevnte!\n";
}
} while(valg != 'Q' || valg != 'q');
return 0;
}
I dont know what is happening in your case, but I ran your code and it works just fine for me. Entered 1,4,Q and program exited as expected....Could be a compiler or a DyrLuft class issue(i just removed the inheritance to make it work, also lines from case 2,3,4).
You have:
case '1':
{
Fugl fugl; fugl.les();
} break;
When you run this you create a Fug1 object and then you call the les() function. When you enter an appropriate age in les() the function returns. Since the break; is outside of the case block it is actually breaking the switch statement and going to the end of the loop. Then it cycles back to the top of the loop and makes you enter a selection again. If you move break inside og the case block it functions as it should. This is the changed loop:
do
{
cout << "Hvilken dyreart ønsker du å registrere? (Q for å avslutte)"
<< "\n1) - Fugl \n2) - Fisk \n3) - Insekt \n4) - Skalldyr\n";
cin >> valg;
switch (valg)
{
case '1':
{
Fugl fugl; fugl.les();
break;
}
case '2':
{
Fisk fisk; fisk.les();
break;
}
case '3':
{
Insekt insekt; insekt.les();
break;
}
case '4':
{
Skalldyr skalldyr; skalldyr.les();
break;
}
case 'Q': return 0;
case 'q': return 0;
default: cout << "Velg en av ovennevnte!\n";
}
} while (valg != 'Q' || valg != 'q');