Calculator Program does not compile [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I wrote a program that implements a simple calculator. However, it does not compile. The compiler says that there are 22 errors, and I don't know why.
Desired behavior:
Asks user about the desired operation
Asks user about the parameters
Outputs result
Specific problem or error:
Compilation errors at any occurrence of cin,cout, endl, case and break
Minimal, Complete, and Verifiable example:
#include <iostream>
int main()
{
float area, r, l, h, b;
int choice;
cout<<"\n area of?";
cout<<"\n[1]square \n[2]rectangle \n[3]circle \n[4]triangle"<<endl;
cin>>choice;
switch(choice);
{
case 1:
cout<<"enter length"<<endl;
cin>>l;
area=l*l;
cout<<area<<endl;
break;
case 2:
cout<<"enter height"<<endl;
cin>>h;
cout<<"enter length"<<endl;
cin>>l;
area=l*h;
cout<<area<<endl;
break;
case 3:
cout<<"enter radius"<<endl;
cin>>r;
area=r*r*3.14;
cout<<area<<endl;
break;
case 4:
cout<<"enter height"<<endl;
cin>>h;
cout<<"enter breadth"<<endl;
cin>>b;
area=h*b*0.5;
cout<<area<<endl;
break;
}
return 0;
}

The are two errors (compile time errors, at least). First of all, cin, cout and endl are not known, you have to write them as std::cin, std::cout and std::endl.
The second problem is here:
switch (choice);
Remove that semicolon and it's fine. The reson why it's not working with the semicolon is because then switch (choice); is its own one and done deal, and the statements after it don't make sense without it.
Also, although it's not causing any compile time errors, I would highly recommend that you indent your code properly. mjcs edited the code you provided for you, it now looks much nicer and it is much easier to find the errors this way. In a big program, it is absolutely vital that the code is indented well, otherwise it's very hard to work with.

Related

What is the difference between the two codes in C++? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I was trying the problem Hash Tables: Ice Cream Parlor on Hackerrank. It is a simple question, but here is the bizzare situation i got to. How does the change of data structure matter?
Case 1:
void whatFlavors(vector<int> cost, int money) {
int ans1,ans2;
vector<int> arr(100,0); //notice this
for(int i=0;i<cost.size();i++){
if(arr[money-cost[i]]!=0){
ans1=i+1;ans2=arr[abs(money-cost[i])];
if(ans1>ans2){
cout<<ans2<<" "<<ans1<<endl;
}else{
cout<<ans2<<" "<<ans1<<endl;
}
break;
}
else{
arr[cost[i]]=i+1;
}
}
}
And output is:
Case 2:
code:
void whatFlavors(vector<int> cost, int money) {
int arr[100]={0}; //notice this
int ans1,ans2;
for(int i=0;i<cost.size();i++){
if(arr[money-cost[i]]!=0){
ans1=i+1;ans2=arr[abs(money-cost[i])];
if(ans1>ans2){
cout<<ans2<<" "<<ans1<<endl;
}else{
cout<<ans2<<" "<<ans1<<endl;
}
break;
}
else{
arr[cost[i]]=i+1;
}
}
}
output:
Let's just notice this part of your code:
if(arr[money-cost[i]]!=0){
ans1=i+1;ans2=arr[abs(money-cost[i])];
This means that your expect money-cost[i] to be negative for some values of i. So you end up reading locations that are outside your array (vector or array) which will lead to undefined behavior in both cases.

C++ While Loop to work

Since I know the basics of Python (3), I decided to take the programs I did in Python and type them in C++ to get the hang of C++.
Problem: When you type "TheEnd" for the name, I wish the program to end, but for some reason if you type "TheEnd" it will ask for the other fields once, and then end. Is there a way for the user to type "TheEnd" when asked for a name and the program just ends? (I tried putting the while loop in different areas, but to no avail.)
Here is what I have:
#include <iostream>
#include <string>
//While loop.
using namespace std;
main()
{
string name;
string major;
float hours, qualityPoints, GPA;
while (name!="TheEnd") //Here's the while loop
{
cout<<"Please enter your name. "<<endl;
cin>>name;
cout<<"Please enter your major. "<<endl;
cin>>major;
cout<<"List the hours you've completed so far. "<<endl;
cin>>hours;
cout<<"List how many quality points you have. "<<endl;
cin>>qualityPoints;
GPA = qualityPoints / hours;
if (GPA >= 3.4 and hours >= 12)
{
cout<<name<<endl;
cout<<major<<endl;
cout<<"You made the Dean's List."<<endl;
}
else
{
cout<<"You did not make the Dean's List."<<endl;
}
}
}
It is asking because your condition is tested at the beginning and then after asking all fields.
The smallest change of your code would be following changes:
for(;;) // Former while(name!="TheEnd")
{
cout<<"Please enter your name. "<<endl;
cin>>name;
if(name=="TheEnd")
break;
Some explanation:
Usually it is common practice to use for(;;) instead of while(true) as endless loop. The reason for that lies in the fact the some compiler emit(ted) warnings for constant expressions in if/while (for e.g. VS 2005 which was AFAIK widely used). In most professional projects warnings are taken as error.
Every loop (for/while) can be exit by using break. So you have no loop condition but a exit condition. I decided to wrote this solution because it needed the smallest change to your sample code. Also there is no (easy) way to keep your breaking condition as part of the while condition.
Keep the while(name!="TheEnd") and only add the if after the cin is not good pratice. You produce "cargo cult programming" code with that.

Pseudo- andom number generation error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am the very beginner of the developing field, and I am facing a problem in Pseudo code random error in C++ language.
I think the Error in my program is:
{
srand(time (NULL));
}
Please help me how can I remove this error and the reason of error.
The program I developed is below,
#include<iostream>
using namespace std;
main()
{
int lowerRange;
int upperRange;
lowerRange=1;
upperRange=1;
int secretNumber;
int guess;
guess=10;
cout<<"My Student ID is BC130400789 "<<endl;
cout<<"Enter lower range : ";
cin>>lowerRange;
cout<<"Enter upper range : ";
cin>>upperRange;
cout<<"Computer is calculating a random secret number in the given range...Done!"<<endl;
cout<<"\nPlease guesss the secret number in the range ["<<lowerRange<<" - "<<upperRange<<"]: ";
cin>>guess;
if(guess<10)
{
cout<<"You won! You guess the correct number.. ";
}
else
{
cout<<"Oooppsss...Your entered number is too high...Computer won"<<endl<<endl;
}
{ srand(time (NULL));}
secretNumber = rand()%10+1;
cout<<"Secret number was: "<<secretNumber<<endl<<endl;
}
system("pause");
}
main HAS TO return int
rand() is defined in cstdlib which you don't include
You also need to include ctime for time function
As said by G. Samaras you shouldn't use system("pause") (also you don't include required header for it) and you have mismatched {}.
I would also recommend you reading something about code formatting.
You have an extra bracket at the end. Remove this and the system("pause"); and you will get no errors. Also main() usually returns an int, thus make it int main().
system(“pause”); - Why is it wrong?

How can I give the option of repeating the input for a switch statement in C++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Hi I'm playing around with basic looping techniques and I'm trying to make the following code work. When the user inputs a number other than those allowed it will go to the default where I want to give them the option to try again (without just subbing the whole code into the default) or to just exit.
#include <iostream>
using namespace std;
int main(){
int input;
char ans;
cout<<"Hi please pick 1, 2 or 3: ";
cin>> input;
switch(input){
case 1:
cout<<"\nYou picked one\n";
break;
case 2:
cout<<"\nYou picked two\n";
break;
case 3:
cout<<"\nYou picked three\n";
break;
default:
cout<<"\nYou didn't pick a valid option.\nWould you like to try again?(y/n)";
cin>>ans;
if(ans== 'y'){
break;
}else{
continue;
}
}
}
When I run this I get the error that continue isn't in any loop. I'm not really quite sure how to use the continue statement. Any help with this would be greatly appreciated.
Put your switch statement inside a loop (while(1)) or (for(;;)), then it will work.
From http://en.cppreference.com/w/cpp/language/continue:
continue statement:
Causes the remaining portion of the enclosing for, range-for, while or do-while loop body skipped.
Used when it is otherwise awkward to ignore the remaining portion of the loop using conditional statements.
You need to put the core of your function in a for loop or while loop.
bool stop = false;
while ( !stop )
{
cout<<"Hi please pick 1, 2 or 3: ";
cin>> input;
stop = true;
switch(input){
case 1:
cout<<"\nYou picked one\n";
break;
case 2:
cout<<"\nYou picked two\n";
break;
case 3:
cout<<"\nYou picked three\n";
break;
default:
cout<<"\nYou didn't pick a valid option.\nWould you like to try again?(y/n)";
cin>>ans;
if(ans== 'y'){
stop = false;
}
}
}

Project in c++, making a phonebook [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I tried and looked everywhere on the internet, I can't seem to find much.
Now, without too much talking, to the problem I have: I have to make a project for college that consists of making an "electronic phone-book" using OOP programming logic in C++. The materials I`ve received to do this are extremely vague so I must do on my own somehow.
Here is the code I have done so far(with help from the internet):
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream.h>
#include <string.h>
#include <fstream.h>
void op1()
{
printf("\n Add contact");
getch();
}
void op2()
{
printf("\n Delete contact");
getch();
}
void op3()
{
printf("\n Edit a contact");
getch();
}
void op4()
{
printf("\n Find a contact");
getch();
}
void op5()
{
printf("\n Sort the contacts");
getch();
}
void op6()
{
printf("\n 'About the program, details etc. etc.");
getch();
}
void print_menu()
{
system("cls"); // clearing window
printf("\nMenu:");
printf("\n##############################\n");
printf("\n1. Add contact");
printf("\n2. Delete contact");
printf("\n3. Edit a contact");
printf("\n4. Find a contact");
printf("\n5. Sort the contacts");
printf("\n6. About");
printf("\n7. Exit");
printf("\n\n##############################");
printf("\n\nInput your option: ");
}
// Text centering function - begin
void centerText(char* s)
{
int l=strlen(s);
int pos=(int)((80-l)/2);
for(int i=0;i<pos;i++)
cout<<" ";
cout<<s<<endl;
}
// Text centering functon - end
void main()
{
{
printf("\n 'My University' 'My City' ");
printf("\n Faculty of Electrical Engineer and Computer Science");
printf("\n Study program used: C++\n\n");
centerText("C++ Project");
centerText("<The Phonebook>");
printf("\n");
centerText("<my name, Year I of study, Group>");
printf("\n");
printf("\n");
centerText("<june.2013>");
system("pause>nul"); // Screen is paused until a key is pressed (to allow this text to be viewed)
}
// ... Sequence for password verification ...
{
char password[20], my_password[20]="2013";
system("cls");
printf("WARNING!\n");
printf("Authentication required!\n");
printf("\nType input password: ");
scanf("%19s",password);
if (strcmp(password, my_password)!=0)
{
printf("\n\nIncorrect password !!!\n");
printf("The program will now exit...\n");
getch();
return;
}
printf("\n\nPassword is correct !\n");
printf("The program is executed !\n");
getch();
}
char optiune;
// ... Sequence for option choosing ...
do
{
print_menu();
fflush(stdin);
cin>>optiune;
switch(optiune)
{
case '1': op1(); break;
case '2': op2(); break;
case '3': op3(); break;
case '4': op4(); break;
case '5': op5(); break;
case '6': op6(); break;
case '7': exit(0);
default : printf("\n\nIncorrect option !");
fflush(stdin);
getch();
}
}
while(1);
}
The idea was that I could maybe use this menu in a way like, just inserting in one of the op() functions the redirect to another file, which is 1 function in a separate file.
So I would then have this program as a main program and each function that "adds, edits, deletes ..etc will be outside of this program and I would deal with them separately.
Thing is ..I have no clue in doing so. I've looked in the "header" working system and I didn't really find anything of value there. Maybe I don't know to look but trust me I've really tried.
Any feedback is much appreciated, but remember I am extremely newbie in this. Please, if you can, explain with as much detail as you can. I appreciate anyone who read this entire thing. I will thank the beginning.
You say you can't find help anywhere, but then you say "I have to make a project for college". So presumably you already have instructors and/or professors to help you learn? Other than that, any introductory C++ book ever written will cover what you're asking for, here.
You say "using OOP programming logic in C++", yet you don't use any OOP other than built in IO classes.
Indent your code properly.
Don't use these:
#include <conio.h>
getch()
system("cls")
You're mixing calls to printf() with std::cout, and calls to scanf() with std::cin - pick one or the other, and never use scanf().
If you're using C++, using std::string is better than this:
void centerText(char* s)
The cast here is unnecessary, when you're assigned to an int it'll automatically convert:
int pos=(int)((80-l)/2);
main() returns int, don't do this:
void main()
You can't fflush(stdin), flushing is not defined on input streams.
Don't put things on one line like this, because it looks awful:
case '1': op1(); break;
It's better to return 0 than exit(0) under normal circumstances, as exit(0) will not destroy your objects.
In many applications there are three main components to building the solution. There is the View, which is how you interact with the user. Your work so far looks as though you are building a fairly sensible command line interface for that. Then there is the back end where the contacts will be stored. This could be a file, a database or some kind of JSON or XML structure. In between is the controller that keeps the view and database in sync and executes commands and queries from the user. Maybe this is going too far for your coursework and you are happy if everything is forgotten when you kill the program. In that case you need a memory-based structure to hold the data. I suggest you make a class to hold all the fields in your contact and store in in a std::vector<Contact>.