A "misplaced else" error in this C++ program - c++

I cannot seem to fix the "misplaced else" error in the code below. This code should collect and compute for term grades and give remarks depending on the score.
#include <conio.h>
#include <stdio.h>
main()
{
char name[20];
int exam, q1, q2, q3, ass, sw, att, avgq, CS, TG;
clrscr();
printf("Name: ");
gets(name);
printf("\nExam: ");
scanf("%d", &exam);
printf("\nQuiz #1: ");
scanf("%d", &q1);
printf("\nQuiz #2: );
scanf("%d", &q2);
printf("\nQuiz #3: ");
scanf("%d", &q3);
printf("\nAssignment: ");
scanf("%d", &ass);
printf("\nSeatwotk: ");
scanf("%d", &sw);
printf("\nAttendance: ");
scanf("%d", &att);
CS = (0.4*ass) + (0.4*sw) + (0.2*att); // class standing //
avgq = (q1 + q2 + q3)/3; // Average quiz //
TG = (0.4*exam) + (0.3*avgq) + (0.3*CS); // Term grade //
if(TG >= 90)
printf("Term Grade: %d", TG);
printf("Remarks: EXCELLENT");
else if (TG>=80 && TG<=89)
printf("Term Grade: %d", TG);
printf("Remarks: SATISFACTORY");
else if (TG>=76 && TG<=79)
printf("Term Grade: %d", TG);
printf("Remarks: GOOD");
else if (TG == 75)
printf("Term Grade: %d", TG);
printf("Remarks: PASSING");
else if (TG<74)
printf("Term Grade: %d", TG);
printf("Remarks: FAILED");
else
printf("Invalid Input. Try again");
getch();
return 0;
}

Uh oh! Noob alert! Just kidding; we all have to start somewhere ;)
So do not worry, fair maiden! The problem lies here:
When you declare an if statement, you must encompass the body of the if statement with curly braces. If you don't do that, only the first line below the if statement will be run. Here's an example:
// Here, both do something 1 and do something 2 are being run in the 'if' statement
if (something) {
do something 1;
do something 2;
}
// Here, only do something 1 will get run inside the 'if' statement
if (something)
do something 1;
do something 2;
So back to your problem. You must put curly braces {} around the code in an if statement if the if statement body consists of more than one line.
if (something)
do something 1;
do something 2;
else
do something 3;
is equivalent to
if (something)
do something 1;
do something 2;
else do something 3;
That is why your else statement throws an error. Each else must have an if before it.

C++ doesn't use indentation to determine the ends of statements. You need braces if you want more than one statement.
Instead of:
if (a)
b;
c;
else
d;
Use:
if (a) {
b;
c;
} else {
d;
}

If you have more than 1 line under an if or else, they must be contained in curly braces, like this:
if(TG>=90)
{
printf("Term Grade: %d",TG);
printf("Remarks: EXCELLENT");
}
else if (TG>=80 && TG<=89)
{
printf("Term Grade: %d",TG);
printf("Remarks: SATISFACTORY");
}

Related

problem in printing out the character in console

In my code I did this
int y=strcmp(s,s1);//before this I converted all the uppercase of the string input as lower case.
if(y==0)
{
cout<<"0"<<endl;
}
else if(y >= 1)
{
cout<<"1"<<endl;
}
else if(y<1)
{
cout<<"-1"<<endl;//problem was here
}
so i took aaaa and aaaA as input and expected 0 as output . But it gave me -1 as output.
But in my code when I wrote this:
int y=strcmp(s,s1);
if(y==0)
{
cout<<0<<endl;
}
else if(y >= 1)
{
cout<<1<<endl;
}
else if(y<1)
{
cout<<-1<<endl;
}
It gave me the right answer.
My question why this happened?
you removed " " in the cout. Can you show the error code you're getting in the first round?

Making it loop back to the beginning

I am pretty new to the coding world so my coding isn't that great. I am doing a project and trying to make it loop back to the beginning after the calculations.
I'm not 100% on what I'm doing so I do apologize ahead of time. If I run it like this it gives me the error of having a "else" without a previous "if". I had it in a do loop but a friend told me I could just do it like this. Thank you in advance for you tips/advice.[The code][1] Sorry I don't know how to post the code in this block.Edit, Not sure what to add as my while statement at the end to make it loop back.
#include <iostream>
using namespace std;
int main () {
char C = 'C';
char c = 'c';
char x = 'x';
char X = 'X';
char s ='s';
char S ='S';
char r = 'r';
char R = 'R';
char t = 't';
char T = 'T';
do{
char C = 'C';
char c = 'c';
char x = 'x';
char X = 'X';
char s ='s';
char S ='S';
char r = 'r';
char R = 'R';
char t = 't';
char T = 'T';
cout<<"Please enter C for circle , S for square , R for rectangle , T for triangle(right) , X to exit"<<endl;
cin >> x;
if ((x==C)||(x==c)){
cout<<"Please enter radius"<<endl;
float c1;
float c2;
cin>>c1;
c2=c1*2*3.14;
cout<<"The Area= "<<c2<<endl;
}else if ((x==s)||(x==S)) {
cout<<"Please enter side"<<endl;
float s1;
cin>>s1;
float s2;
s2=s1*2;
cout<<"The radius= "<<s2<<endl;
}else if ((x==t)||(x==T)) {
cout<<"Please enter leg"<<endl;
float t1;
cin>>t1;
cout<<"Please enter leg 2"<<endl;
float t3;
cin>>t3;
float t2;
t2=(t3*t1)/2;
cout<<"The radius= "<<t2<<endl;
}else if ((x==r)||(x==R)){
cout<<"Please enter Width"<<endl;
float w1;
cin>>w1;
cout<<"Please enter Length"<<endl;
float w2;
cin>>w2;
float w3;
w3=w1*w2;
}else ((x==X)||(x==x));{
break;
}
}while ((x=!c)||(x=!C)||(x!=s)||(x!=S)||(x!=t)||(x!=T)||(x!=x)||(x!=X)||(x!=r)||(x!=R));
}
}
}
The problem is with your first else statement, you inserted a semicolon accidentally.
else ((x==5)||(x==5));
Remove the semicolon and you should be fine!
Also it should be else if instead of else. Basically, the format goes like if, else if, else.
variable=true
if(variable==true)
{
. // do something
}
else if(variable==false)
{
//do something else
}
else
{
// do something else
}
An else statement doesn't have a condition. It's for when it doesn't match all of these, do this! If you still don't understand, this should give you a good understanding of if, else if, else statements
Again, if you are struggling, please take a read here. It explains it well:
https://www.tutorialspoint.com/cplusplus/cpp_if_else_statement.htm
It seems like you want this to infinitely repeat for the user, and you're trying to use a do-while loop.
do {
// Whatever you're doing
} while (condition);
Usually you can create some type of bool and set it to true when you want to exit the loop, so you can do:
bool getMeOut = false;
do {
// Some Stuff
if (condition for exit)
getMeOut = true;
} while (getMeOut == false);
And you'll be stuck in that loop until you set getMeOut to true!
Best of luck!

Logic operators in if statments

So i am writing a calculator as an exercise in c++, were you first select operators +, -, * or / by inputting a, s, m or d. The calculator works fine, except for a filter i set up to respond with an error if the user inputs something other than a, s, m or d. The filter is an if statement:
if(Opperator=='a'||'s'||'m'||'d')
{
//some code
}
else
{
//"Operatorfault"
cout <<"opperatorfeil";
}
Even though the "operator" has other char values than those the if statement is suppose to execute, the code within the if statement is still executed. The whole code is below. The outputs and variables are in Norwegian, but i have tried to translate in the comments.
#include <iostream>
using namespace std;
//The calculator function
int Kalkulator(int IN1, int IN2, char Opperator)
{
int Svar;
//Detects witch operator the user choose, and preforms the assigned operation
if(Opperator=='a')
{
Svar=IN1+IN2;
}
if(Opperator=='s')
{
Svar=IN1-IN2;
}
if(Opperator=='m')
{
Svar=IN1*IN2;
}
if(Opperator=='d')
{
Svar=IN1/IN2;
}
//Returns the answer
return Svar;
}
int main()
{
//Input a, s, m or d for addition, subtraction, multiplication or division, respectively
cout <<"Skriv \"a\" for addisjon, \"s\" for subtraksjon, \"m\" for multipliksjon, og \"d\" for divisjon";
cout <<endl;
cout <<endl;
char Opperator;
cin >>Opperator;
cout <<endl;
//Checks if the input is valid
if(Opperator=='a'||'s'||'m'||'d')
{
cout <<"Skriv inn det første tallet du vil gjøre opperasjonen på, trykk derreter enter, og skriv inn det andre";
cout <<endl;
cout <<endl;
int IN1;
int IN2;
cin >>IN1;
cin >>IN2;
cout <<endl;
//"The answer is"
cout << "Svaret er: ";
//Calls the calculator function, and inputs the values it has gathered, then prints the answer
cout <<Kalkulator(IN1, IN2, Opperator);
}
else
{
//"Operatorfault"
cout <<"opperatorfeil";
}
return 0;
}
The error is in your if statement. In C++, when you are comparing the same variable to multiple values, for example if opperator is a, m, s, d, you need to restate the variable for each comparison.
if( Opperator=='a' || Opperator=='s' || Opperator=='m' || Opperator=='d' )
Instead of your current if statement.
Also, as a tip, a switch statement is much better in these cases, you can simply state
int ans;
switch (customerPackage) {
case 'a':
ans = int1 + int2;
case 's':
ans = int1 - int2;
case 'd':
ans = int1 * int2;
case 'm':
ans = int1 / int2;
default:
string ans;
ans = "invalid input";
}
cout <<ans;
This is wrong:
if(Opperator=='a'||'s'||'m'||'d')
you can NOT test for equality (or inequality) like this. The code executes as the equivalent of
if (Operator == (result of boolean ORs))
You have to test for equality individually:
if ((op == 'a') || (op == 's') || etc...)
Why not just break it out like so,
if (Opperator == 'a' ||
Opperator == 's' ||
Opperator == 'm' ||
Opperator == 'd')
{
// Good values
}
else
{
// Bad values
}
if(Opperator=='a'||'s'||'m'||'d')
It checks whether Opperator is equal to 'a', if not then 's' always returns true and so all logic becomes true.
You can use if statement:
if (Opperator == 'a' || Opperator == 's' || Opperator == 'm' || Opperator == 'd') {
// my calc works well
} else {
// again my calc works well
}
OR you can use switch:
switch(Opperator) {
case 'a':
case 's':
case 'm':
case 'd': // do normal operation here
break;
default: // error handle
break;
}
You must test each char for equality:
if(Opperator=='a'||Opperator=='s'||Opperator=='m'||Opperator=='d') {
...execute
} else {
...execute something else
}
If you want to be fancy you can use algorithm::anyOf().
#include <algorithm>
const std::vector<char> validValues{'a','s','m','d'};
if(any_of(validValues.begin(),
validValues.end(),
[&](const char &x) { return x == Opperator; }) {
// good values
} else {
// bad values
}

segmentation fault in swap function

im busy writing a line of code for my study.
I already have gotten quite far on the assignment but i keep running into the same problem.
On the swap function i keep running into a segmentation fault when a character is inputted(word & word2) that is not in the main 'dictionary' string.
Could someone explain to me what is causing the problem and how i can solve it? Sorry if anything isnt clear, i've just started learning c++.
code where segmentation fault occures:
void swapWords(char **dict, char *word, char *word2)
{
int i;
int d;
int x;
int y;
char *tmp;
while (1){
for(i = 0; i < MAX_NUMBER_OF_WORDS; i++)
{
if(strcmp(word, dict[i]) != 0)
{
if(i == MAX_NUMBER_OF_WORDS -1)
{
printf("Cannot swap words. Atleast one word missing in the dictionary.\n");
goto error;
}
}
else
{
x = i;
break;
}
}
for(d = 0; d < MAX_NUMBER_OF_WORDS; d++)
{
if(strcmp(word2, dict[d]) != 0)
{
if(d == MAX_NUMBER_OF_WORDS -1)
{
printf("Cannot swap words. Atleast one word missing in the dictionary.\n");
goto error;
}
}
else
{
y = d;
break;
}
}
tmp = dict[x];
dict[x] = dict[y];
dict[y] = tmp;
error: break;
}
}
The entire code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#define MAX_NUMBER_OF_WORDS 10
void swapWords(char **dict, char *word, char *word2)
{
int i;
int d;
int x;
int y;
char *tmp;
while (1){
for(i = 0; i < MAX_NUMBER_OF_WORDS; i++)
{
if(strcmp(word, dict[i]) != 0)
{
if(i == MAX_NUMBER_OF_WORDS -1)
{
printf("Cannot swap words. Atleast one word missing in the dictionary.\n");
goto error;
}
}
else
{
x = i;
break;
}
}
for(d = 0; d < MAX_NUMBER_OF_WORDS; d++)
{
if(strcmp(word2, dict[d]) != 0)
{
if(d == MAX_NUMBER_OF_WORDS -1)
{
printf("Cannot swap words. Atleast one word missing in the dictionary.\n");
goto error;
}
}
else
{
y = d;
break;
}
}
tmp = dict[x];
dict[x] = dict[y];
dict[y] = tmp;
error: break;
}
}
void removeWord(char **dict, char *word)
{
int i;
int d;
for(i = 0; i < MAX_NUMBER_OF_WORDS; i++)
{
if(strcmp(dict[i], word) == 0)
{ dict[i] = NULL;
for(d = i+1; d < MAX_NUMBER_OF_WORDS; d++)
{ if(dict[d] == NULL)
{ dict[i] = dict[d-1];
dict[d-1] = NULL;
break;
}
}
break;
}
}
}
void printDict(char **dict)
{
int i = 0;
if(dict[0] == NULL)
{
printf("The dictionary is empty.\n");
}
else{
while (dict[i] != NULL)
{
printf("- %s\n", dict[i]);
i++;
}
}
}
void addWord(char **dict, char *word)
{
int d;
char *word1;
for(d = 0; d < MAX_NUMBER_OF_WORDS; d++)
{
if (dict[d] == NULL)
{
word1 = (char*) malloc(sizeof(char)*(strlen(word) + 1));
strcpy(word1, word);
dict[d] = word1;
break;
}
}
}
int numberOfWordsInDict(char **dict)
{
int i = 0;
int d;
for (d = 0; d < MAX_NUMBER_OF_WORDS; d++){
if(dict[d] != NULL)
{
i++;
}
}
return i;
}
int main()
{
char *dict[MAX_NUMBER_OF_WORDS] = {};
char word[36];
char word2[36];
char c;
int i;
while(printf("Command (a/p/r/s/q): "))
{
scanf(" %c", &c);
switch (c){
case 'p': printDict(dict);
break;
case 'a': printf("Enter a word: ");
scanf("%s", word);
addWord(dict, word);
break;
case 'n': i = numberOfWordsInDict(dict);
printf("%d\n", i);
break;
case 'r': printf("Remove a word: ");
scanf("%s", word);
removeWord(dict, word);
break;
case 's': printf("Swap two words:\n");
printf("Enter first word: ");
scanf("%s", word);
printf("Enter second word: ");
scanf("%s", word2);
swapWords(dict, word, word2);
break;
case 'q': return 0;
}
}
}
It will be most helpful to your studies as a student if you find the actual error yourself, though Marco and πάντα ῥεῖ may be right. However, here are a few things to think about, as this will definitely not be your last segfault problem as a programmer (I had at least 20 this month alone).
A segmentation fault is almost always caused by the code trying to modify or read memory that it doesn't have permission to read or modify. When the program starts, it is given a chunk of memory (RAM) to work with. For security reasons, no program is allowed to work with memory outside of that chunk. There are other limitations at play too.
As a general rule, if you try to read memory past the end of an array, you have a high risk of getting a segfault, or in other cases, garbled data. The official word on this actually comes from C, C++'s parent language, in that accessing past the end of an array causes "undefined behavior". Or, as it was once said on USENET, "it is legal for the compiler to make demons fly out of your nose". The behavior is totally unpredictable. Thankfully, that undefined behavior usually IS a segfault.
By the way, if you try to access an uninitialized array, similar weirdness can happen.
NOW, since you are accessing the elements of your array via a loop, another possible cause is that your loop is continuing beyond where you think it is. Sometimes it is helpful to modify your code so that the loop's iterator (i in your case) is printed out each iteration. This can help you catch if the loop is going beyond where it should.
In short, check...
Did I initialize all of my arrays before I tried to read or write
them?
Are my loops starting and stopping where I expected? Check for
"off-by-one" errors (i.e. starting at 1 instead of 0), infinite
loops (forgot to increment the iterator or the stop condition is
never true), and other logical errors.
Am I trying to read/write past the end of the array?
If I'm working with a C-string, did I forget the NULL terminator?
In addition to your debugger, which you should learn how to use well, tools like valgrind are instrumental in finding the cause of memory errors. Oftentimes, it can point you to the exact line of code where the segfault is occuring.
I had figured out myself the problem was in the strcmp. I know that figuring out a problem by myself is the best way to learn and I tried, but I just couldn't figure out why it was returning a seg fault. As this is my fifth assignment I'm only just getting to know how array's and pointers work. I assumed that the array was already initialized as 'NULL', as seen I was already comparing the pointer to 'NULL' in the addWord function. To assume this is ofcourse very stupid of me. I might not have figured the problem out by myself, yet it is still something I will not be forgetting anymore.
Most probably the segmentation fault happens here:
if(strcmp(word, dict[i]) != 0)
Infact it is quite likely that that i > becomes bigger than the size of your dict and if your dict has 3 elements and you try to access the 4th you are accessing an unknown area or ram and that causes a segmentation fault.
The solution is to make sure your for loop stops at the last element of the dictionary with the solution πάντα ῥεῖ has proposed in the above comment.

switch case loop statement

I am having a problem with my one assignment. I made one function name chequingsaving and when I call this function, it prints some data which is correct, but when I entered character depends on my selection of account it directly goes out of the loop. If I entered a correct character value, then same thing happens. That function code is below. Help me to find out my mistake. The thing is I also used a switch case, but still it directly goes to default. Same thing happens with if/else loop.
void chequingsaving() /*Chequing and saving account function*/
{
char a;
double r, Initialamount = 0;
printf(" c) Chequing\n");
printf(" s) Savings\n");
printf("Which account would you like to use?\n");
scanf("% c", &a);
if (a == 'c' || a == 'C')
{
printf("Please enter the amount for deposit\n");
scanf("% lf", &r);
Initialamount = Initialamount + r;
printf("Your chequing account balance is=%lf", Initialamount);
}
else
if (a == 's' || a == 'S')
{
printf("Please enter the amount for deposit\n");
scanf("%lf", &r);
Initialamount = Initialamount + r;
printf("Your chequing account balance is=%lf", Initialamount);
}
else
printf("Invalid character\n");
}
Remove the space in scanf:
scanf("%c", &a);
and also in the following scanf:
scanf("%lf", &r);
Your scanf is not correct, you have space "% c".