I've been messing around with my very basic C++ knowledge (been programming for two days), attempting to write a program that calculates user input around phi (1.61803399).
Here's the code, apologies if its a mess:
#include <iostream>
#include <math.h>
using namespace std;
//Prototypes:
float phiExpo;
float phiNegExpo;
float opt1f(float phi, float userInput){
return userInput * phi;}
float opt2f(float phi, float userInput){
return userInput / phi;}
float opt3f(){
return phiExpo;}
float opt4f(){
return phiNegExpo;}
float phiExpof(float phi, float userInput){
pow(phi,userInput);}
float phiNegExpof(float phi, float userInput){
pow(phi,-userInput);}
//Execute program:
int main(){
float userInput;
int userChoice;
float phi = 1.61803399;
float phiExpo;
float phiNegExpo;
cout<<"I want to (press corresponding number, then enter):"<<endl;
cout<<endl;
startchoices:
cout<<"1. Multiply by phi:"<<endl;
cout<<"2. Divide by phi:"<<endl;
cout<<"3. Exponentiate phi:"<<endl;
cout<<"4. Negatively exponentiate phi:"<<endl;
cout<<endl;
cin>>userChoice;
cout<<endl;
switch (userChoice){
case 1:
cout<<"Enter number for multiplication: ";
cin>>userInput;
return opt1f(phi, userInput);
case 2:
cout<<"Enter number for division: ";
cin>>userInput;
return opt2f(phi, userInput);
case 3:
cout<<"Enter number for to exponetiate phi by: ";
cin>>userInput;
return opt3f();
case 4:
cout<<"Enter number for negatively exponentiate phi by: ";
cin>>userInput;
return opt4f();
default:
cout<<"Please enter a number from 1 to 4.";
cout<<endl;
cout<<endl;
goto startchoices;
}
cin.get();
}
Anyway, upon entering a number at the first prompt (1-4), the program simply crashes to the desktop, and I can't figure out why.
Any help would be much appreciated.
Are you sure it crashes? The code simply returns the value of the operation (casted to an int, as this is the return type of main). I would suggest that you should print it using cout << opt4f().
The problem comes with the return statements in your switch.
The function main() is special in that the return value tells the operating system whether the program was successful. If the return value of main() is 0, then everything worked fine. If it is nonzero, then there was an error.
In your code, you are returning the value of opt1f(phi, userInput), optef(phi, userInput), etc. These values are likely non-zero, thus telling the operating system that your program failed.
Your program doesn't close on the switch statement when I run it; I get your second text.
There are a few problems I see though:
First, as faster people have noted, your returns quit out of the application instead of outputting the answer.
Secondly, after you change your code to cout rather than return, you will want to put in a "break;" so you don't run the code in every condition after the current one.
Thirdly, you might want to change the goto into an input loop and add a quit option to your menu. This is more of a stylistic choice, but I think you will find that goto's in c/c++ are harder to debug in the future.
-edit: for formatting-
Well, assuming you wanted to be able to do more than one thing per program run, and to get rid of the goto, you could do something like:
boolean quitting = false;
do {
cout << "1) Menu item 1" << endl << "2) Quit" << endl;
cin.get(userchoice);
switch(userchoice) {
case 1:
cout << "Please enter input for option 1: ";
cin >> userInput;
cout << case1function(userInput);
break;
case 2:
quitting = true;
break;
default:
cout << "Please read menu" << endl;
}
}while (!quitting);
In this case, the returns exit the main() function, leading to a clean program termination.
The program doesn't crash, it exits because that's what it is supposed to do. The return statement means that the execution will exit the current function, and in case of the current function being main - it will exit the program.
The value of the return is the value which the program will return to the OS. If it's not 0 - the OS will think the program exited abnormally, but in your case - it's just the value of the calculation.
Related
I'm getting a compiler error when trying to build the code below and I don't quite understand what is failing and why.
It's pointing to line 45 (cin>>x[ctr]) with a "no type named 'type' in 'struct std::enable_if<false, std::basic_istream&>'" message.
I've just started coding a few days ago and English is not my native language. Apologies if this question is below the community's paygrade. Hope you can point me in the right direction.
cpp.sh/34sm3
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iomanip>
//#include "_pause.h"
using namespace std;
//////////////////////////////////////////////////////////////////
// NOTE
// This is your program entry point. Your main logic is placed
// inside this function. You may add your functions before this
// "main()", or after this "main()" provided you added reference
// before this "main()" function.
//////////////////////////////////////////////////////////////////
//Write a program that can divide six non-zero integers (two integers per division) from the user and display the result to the user.
//Create a function that will perform the division operation. Display only the non-decimal part of the quotient.
float quot (int num1, int num2)
{
return num1/num2;
}
int main()
{
// ************************** TO DO **************************
// Place your code logic after this comment line
// ***********************************************************
int x[6];
cout<<"Enter 6 integers to divide: ";
for(int ctr=0; ctr<6; ctr++)
{
cin>>[ctr];
if(x[ctr]==0)
{
cout<<"Invalid number! Please enter a non-zero value: ";
cin>>x[ctr];
}
}
cout<<"The quotient of the first pair is: " << quot(x[0],x[1]) <<endl;
cout<<"The quotient of the second pair is: " << quot(x[2],x[3]) <<endl;
cout<<"The quotient of the third pair is: " << quot(x[4],x[5]) <<endl;
system ("pause");
return EXIT_SUCCESS;
}
Are cin statements inside for loops not allowed in C++?
i guess you need to replace cin>>[ctr] with cin>>x[ctr].....this might fix your error.
For starters the function quot should be written like
float quot (int num1, int num2)
{
return static_cast<float>( num1 ) / num2;
}
Otherwise the return type float does not make a great sense because in this expression num1 / num2 there is used the integer arithmetic.
It is obvious that in this statement
cin>>[ctr];
there is a typo. You forgot to specify the array name x
cin >> x[ctr];
Also it will be better to subsritute this if statement
if(x[ctr]==0)
{
cout<<"Invalid number! Please enter a non-zero value: ";
cin>>x[ctr];
}
for a while statement like
while ( x[ctr] == 0 )
{
cout<<"Invalid number! Please enter a non-zero value: ";
cin>>x[ctr];
}
That's all you had to do.
Just change cin>>[ctr] to cin>>x[ctr]
It's on line 41. You need to specify the array name, x before the index [ctr]
Here's your code.
I recommend you to use a debugger to figure out such small human-made-errors yourself.
Also, read your code and try to visualize its flow before asking for solutions.
int main()
{
// ************************** TO DO **************************
// Place your code logic after this comment line
// ***********************************************************
int x[6];
cout<<"Enter 6 integers to divide: ";
for(int ctr=0; ctr<6; ctr++)
{
cin>>x[ctr];
if(x[ctr]==0)
{
cout<<"Invalid number! Please enter a non-zero value: ";
cin>>x[ctr];
}
}
cout<<"The quotient of the first pair is: " << quot(x[0],x[1]) <<endl;
cout<<"The quotient of the second pair is: " << quot(x[2],x[3]) <<endl;
cout<<"The quotient of the third pair is: " << quot(x[4],x[5]) <<endl;
system ("pause");
return EXIT_SUCCESS;
}
I am new at c++ and for an assignment I have a program that requires a switch within a while but i keep getting stuck in an infinite loop
I have tried looking up ways to solve it but since i am not skilled at c++, it is really hard for me to get my error
#include <iostream>
#include <stdio.h>
using namespace std;
int main(void)
{
float length, width, perimeter, area;
char ans;
cout<<"Please enter the length of the rectangle: \n";
cin>>length;
cout<<"Please enter the width of the rectangle: \n";
cin>>width;
cout<<"What do you wish to do with these values?\n";
cout<<"Choose an option from the menu: \n";
cout<<"1 - Calculate Perimeter\n";
cout<<"2 - Calculate Area\n";
cout<<"3 - Quit\n";
cout<<"Please enter your choice: \n";
cin>>ans;
while (ans != '3')
{
printf("give option: "); //found this online
ans = getchar(); //this too
switch (ans)
{
case '1' :
perimeter=2*(length+width);
cout<<"The perimeter of the rectangle with length "<<length<<" and width "<<width<<" is "<<perimeter<<endl;
break;
case '2' :
area=length*width;
cout<<"The area of the rectangle with length "<<length<<" and width "<<width<<" is "<<area<<endl;
break;
default :
cout<<"Invalid Entry, please only select options from menu"<<endl;
}
}
printf("Program finished...\n"); //this was online too
return 0;
}
when i enter the option 2 or 1, there is an infinite loop and i cant seem to fix that.
I am not use to formatting on this site, please excuse the way i formatted my code
getchar() is not the right function to use there. It returns all characters, spaces, newlines, etc.
If you add a line to output the value of ans right after that, you will notice all the values that are assigned to ans.
ans = getchar();
cout << "ans: " << (int)ans << endl;
To skip whitespaces from the stream, use
cin >> ans;
In addition, the logic to get ans inside the while loop is flawed. It should be after the switch statement. Otherwise, your program tries to read ans twice before the first execution of the switch statement.
Here's an updated version of the relevant code that works for me.
cout << "Please enter your choice: \n";
cin >> ans;
while (ans != '3')
{
switch (ans)
{
case '1' :
perimeter=2*(length+width);
cout<<"The perimeter of the rectangle with length "<<length<<" and width "<<width<<" is "<<perimeter<<endl;
break;
case '2' :
area=length*width;
cout<<"The area of the rectangle with length "<<length<<" and width "<<width<<" is "<<area<<endl;
break;
default :
cout<<"Invalid Entry, please only select options from menu"<<endl;
}
cout << "Please enter your choice: \n";
cin >> ans;
}
Here is some help regarding formatting : https://stackoverflow.com/editing-help.
Indent the entire code 4 spaces to the right for a code block.
You must also be able to see the preview below as you keep writing the question.
getchar() isn't the appropriate function to use here. Read about the nuance here : http://www.cplusplus.com/forum/general/193480/
cin will be more appropriate to use.
Also, analyse your code step by step. You have an input taking line outside the while loop, and one inside too. Realise why this is wrong and try fixing it.
Since this is an assignment question, I won't be telling you the answer, but hopefully lead you to understand where you are going wrong.
After you solve the problem, please go back and analyse why your original code did not work. It helps immensely.
So, I'm trying to create a program that has a never ending while loop unless the user pressing a certain key to exit. Now I'm pretty sure that I need to use a while loop but I'm not 100% sure how it works. I've been trying to add error messages to. The user is suppose to enter a numbered grade and it calculates the gpa but I need to validate the user input to make sure it is numeric and between 0 and 100 but after I put the error message in the loop it just is never ending (literally it shows the message down the page over and over without me touching anything)
could someone explain?
int main()
{
int grade; // input
char y; //determines what letter to press to exit
bool validGrade = true; //determines if grade is valid
cout << "Enter percentage grades to convert to grade points. Press [y] to exit.";
cin >> y;
while(validGrade)
{
cout << "Percentage Grade: ";
cin >> grade;
if (!validGrade)
{
cout << "* Invalid input. Please try again and enter a numeric value.";
}
}
}
this is my code^
A C++ while loop,
while (condition) statement
Will repeatedly evaluate statement while condition evaluates to true.
A common issue that results in infinite loops is creating a program that never modifies condition such that it becomes false. For example, in your program, the condition is validGrade, which you've initialized to true. Do you ever modify validGrade? If not, the condition will remain true forever, and thus loop forever.
You mentioned performing checks on grade, but it seems like you haven't implemented them yet. Think about how you could modify the condition variable to ensure that the loop terminates eventually.
I'd also encourage you to read some tutorials to gain a better understanding of while loops. Here's one to start you off.
Your while loop condition has been initialized to true. So it is supposed to run indefinitely. Based on your question, I think what you're trying to do is to check input stream:
int main() {
int grade; // input
char y; //determines what letter to press to exit
bool validGrade = true; //determines if grade is valid
cout << "Enter percentage grades to convert to grade points. Press [y] to exit.";
cin >> y;
while(cin >> grade) {
cout << "Percentage Grade: ";
if (!validGrade) {
cout << "* Invalid input. Please try again and enter a numeric value.";
} } }
I've been searching and trying different things for an hour and can't figure this out. Why doesn't my default work? If I enter 1-4, the output is as expected. However, if I enter any other number or letter, nothing is displayed. I would like the default to display if I enter any other number or letter.
RESOLVED: It was my compiler. Going to use Visual Studio only from now on. (VS didn't show my default at first because I was using it incorrectly.) Thanks to everyone for your responses.
My code:
int main()
{
int num;
cout << "Please enter the code stamped on the storage drive (1-4): ";
cin >> num;
switch (num)
{
case 1:
cout << "The code you entered was 1; therefore, the storage capacity is 2GB." << endl;
break;
case 2:
cout << "The code you entered was 2; therefore, the storage capacity is 4GB." << endl;
break;
case 3:
cout << "The code you entered was 3; therefore, the storage capacity is 16GB." << endl;
break;
case 4:
cout << "The code you entered was 4; therefore, the storage capacity is 32GB." << endl;
break;
default:
cout << "Invalid selection - Please input 1 to 4 only.";
break;
} //end of switch
return 0;
}
The default is working (I've tested it), subject to the following caveats.
First of all, the way your code is structured, you have to enter something. If you just press Enter, nothing will happens because cin >> num will continue waiting for a number.
Secondly, when you enter anything that's not a number, cin >> num fails and leaves num uninitialized. This leads to undefined behaviour in the switch.
You should initialize num (say to 0 or another invalid value) and/or check whether cin >> num has succeeded:
if (cin >> num) {
// the read has succeeded
} else {
// the read has failed
}
Try adding either a '\n' to the end of your default message or a << endl.
Looks like the text from the default is waiting to be flushed.
You could also add a cout.flush(); before the end of your program.
I know this is pointless saying anything as this was a while ago, but for those who have a similar problem look at your code.... case 1: it should instead case '1': the same applies for every other case, then your switch statement will work
So I'm having some problems when using cin and switch statements.
First, the program prompts for an int:
cout << "How many registers would you like to use?: ";
cin >> kassor;
Later on, the user is asked to make a choice:
cout << endl << "Press \"S\" to run the queue simulator and/or make a timestep." << endl;
cout << "Press \"Q\" to quit." << endl << endl;
cout << "Choice: ";
cin >> choice;
switch (choice)
{
case 's':
case 'S':
{
cout << "test";
nya = newCustomers();
break;
}
case 'q':
case 'Q':
{
return 0;
}
}
Here, the 'q' option works fine, but the 's' option does not. It 'hangs', as if still waiting for input. I have tried various cin.ignore() and such, but to no avail.
What puzzles me is that
switch (choice)
{
case 's':
case 'S':
{
cout << "test";
nya = newCustomers();
break;
Gives nothing, but the following:
switch (choice)
{
case 's':
case 'S':
{
cout << "test";
cin.ignore(1024, '\n');
nya = newCustomers();
break;
outputs 'test'.
My main question here is: Is the problem cin or something in the case: s ?
Thank's in advance :
It looks like the function newCustomers is getting hung up on a stray character or two after the input to choice. That would explain why the ignore call "fixes" the problem, and it's the solution suggested in the comment by #TheBuzzSaw.
To see this more clearly, change
cout << "test";
to
cout << "test\n";
or to
cout << "test" << std::endl;
On some systems the console is line-buffered, so you won't see any output until the program writes a newline. Inserting endl flushes the output buffer, so you should see the message even if subsequent code hangs. Or change it to:
cerr << "test\n";
cerr is more aggressive about flushing buffers, precisely because it's used for error output that you don't want to miss.
Short Answer:
I believe cin is failing somewhere or it is the cause of unexpected behavior
I cannot pinpoint it without more code.
Edit: I cannot post a comment on your post, so I figured I would post here. The "hanging" could be an infinite loop. If you are doing something like what I am doing and looping to get input and fail to clear the error bits cin will constantly fail. If you are not cout'ing something each time you ask for input it could just be quietly sitting there looping through that input-gathering function. Put breakpoints in all of your loops and step through with the debugger to verify none of your loops are infinite looping.
Try adding a std::cin.clear(); before the .ignore() in your second test case. See if that stops your hanging.
Explanation:
cin can fail. This can cause weird behavior. A common way for it to fail is if you are reading into an integer and you get character input. Once cin fails it sets a fail bit and from then on, cin does not behave like you would expect.
I would recommend not using a bare cin >> choice, because it can fail and you wont know it. I would abstract this out to a method that gets the proper input you want.
I personally keep a tiny utility library(.h) and .cpp around to include in projects where I am using common functionality I have already coded.
I have a readIntBetween() function which accepts 2 integers and reads from standard input an integer between those two numbers. If the user does not provide the right input (integer over or under bounds, or input containing a character) I ask them to re-enter the input.
In this function I make sure to clear the fail bits when I have detected a failure, and I ignore something like 200 characters to "flush" it out.
Here is the code to my readIntBetween function. I hope it helps you diagnose your error and fix it:
int readIntBetween(int lower, int upper, std::string prompt)
{
bool goodVal = false;
int value = -1;
do
{
std::cout << prompt ;
std::cin >> value;
if ( value >= lower && value <= upper)//check to make sure the value is in between upper and lower
goodVal = true;
else
{
if(std::cin.fail())
{
std::cout << "\tError - invalid format for integer number" << std::endl;
//clear all status bit including fail bit
std::cin.clear();
//flush input buffer to discard invalid input
std::cin.ignore(1000, '\n');
}
else
std::cout << "Value is not valid, must be between " << lower<<" and "<<upper<<"."<<std::endl;
}
}while(!goodVal);
return value;
}
If your cin is being used inside a loop, I recommend a different approach.
char buffer[64];
cin.getline(buffer, 64);
char choice = buffer[0];
switch (choice)
{
...
}
It is possible your cin is not being reset, and any extraneous characters are being fed into the subsequent requests for input. Grab more input and only process its first character.