Can you tell what is the mistake? It compiles and runs ok but the program won't end.
I am using dev c++. The code is:
#include <iostream>
using namespace std;
main()
{
char num;
again:
int usr;
float area;
cout << "\nEnter 1 to calculate area of rectangle\n";
cout << "Enter 2 to calculate area of trapezoid\n";
cout << "\nEnter your choice: ";
cin >> usr;
if (usr == 1)
{
double width, length;
cout << "Enter the width of rectangle: ";
cin >> width;
cout << "Enter the length of rectangle: ";
cin >> length;
area = length * width;
cout << "The area of rectangle is: " << area;
}
if (usr == 2) {
double base1, base2, height;
cout << "Enter the base 1 of trapezoid: ";
cin >> base1;
cout << "Enter the base 2 of trapezoid: ";
cin >> base2;
cout << "Enter the height of trapezoid: ";
cin >> height;
area = (((base1 + base2) / 2) * height);
cout << "The area of trapezoid is: " << area;
}
cout << "\n\ndo you want to do another calculation?";
cin >> num;
{
goto again;
}
if (num == 'y')
{
goto again;
}
if (num == 'n') {
exit(0);
}
}
Never ever use goto, unless you have a very good reason to (which you don't).
cin >> num;{
goto again;
}
I have no idea why you wrote that, but that's the problem. If you would have written it with proper formatting, it would have looked like this
cin >> num;
{
goto again;
}
The bracket {} just changes the scope (useful for variables and such), but doesn't do anything else. The goto again; still gets executed, so you run into an endless loop.
The 2 conditions after it are fine, so just removing { goto again; } will "fix" your issue.
Remove line no 44 in your code
your code
cin >> num;{
goto again;
}
Solution remove
goto again
cin >> num;{
}
This will solve your problem
Related
Good day everyone
I am new to programming and C++.
I have been having some trouble with my program. I want the function culcAverageYearMark to use the variables from the function getMarks but no matter what I have tried it always throw any error like "expected primary expression before 'int' " I have tried everything that I possibly can but no lucky.
#include <iostream>
using namespace std;
void studentDetails()
{
string name, surName, schoolName;
cout << "Enter your name: \n";
cin >> name;
cout << "Enter your surname: \n";
cin >> surName;
cout << "Enter your school name: \n";
cin >> schoolName;
}
void getMarks()
{
int english, mathematics, lifeOrientation, history, computerLiteracy, geography;
cout << "Enter your mark for English: \n";
cin >> english;
while (!(english >0 && english <= 100))
{
cout << "Invalid mark \n";
cout << "Please enter your mark for English: \n";
cin >> english;
}
cout << "Enter your mark for Mathematics: \n";
cin >> mathematics;
while (!(mathematics >0 && mathematics <= 100))
{
cout << "Invalid mark \n";
cout << "Please enter your mark for Mathematics: \n";
cin >> mathematics;
}
cout << "Enter your mark for Life Orientation: \n";
cin >> lifeOrientation;
while (!(lifeOrientation >0 && lifeOrientation <= 100))
{
cout << "Invalid mark \n";
cout << "Please enter your mark for lifeOrientation: \n";
cin >> lifeOrientation;
}
cout << "Enter your mark for History: \n";
cin >> history;
while (!(history >0 && history <= 100))
{
cout << "Invalid mark \n";
cout << "Please enter your mark for History: \n";
cin >> history;
}
cout << "Enter your mark for Computer Literacy: \n";
cin >> computerLiteracy;
while (!(computerLiteracy >0 && computerLiteracy <= 100))
{
cout << "Invalid mark \n";
cout << "Please enter your mark for Computer Literacy: \n";
cin >> computerLiteracy;
}
cout << "Enter your mark for Geography: \n";
cin >> geography;
while (!(geography >0 && geography <= 100))
{
cout << "Invalid mark \n";
cout << "Please enter your mark for Geography: \n";
cin >> geography;
}
}
void calcAverageYearMark();
int main()
{
studentDetails();
getMarks();
calcAverageYearMark();
return 0;
}
void calcAverageYearMark()
{
getMarks(int english, int mathematics, int lifeOrientation, int history, int computerLiteracy, int geography)
float average = (english + mathematics + lifeOrientation + history + computerLiteracy + geography)/6;
}
Yes this is a scope issue.
If you want to calculate something in one function then get that value and send it to another function you want to use this code example...
int calculationA()
{
int a;
//do calulation to a
return a;
}
int calculateB(int b)
{
//b was sent from the main method
//we can use it here
return b;
}
int main()
{
int x = calculationA();
int output = calculationB(x);
//output variable now contains the caclulations after going through both methods
return 0;
}
you cannot access the variable without either making it global or sending it as a parameter. You are experiencing what is called a scope error
The problem you are having really has a couple different causes.
First of all, your function get_marks() has a void return type. That means that it does not return any value when it is run. If you want to get a value out of it you will need to give it a return type. For you needs it would need to return either a reference to an array or a pointer. If you don't know what those are then you should rethink how you are structuring your code so that you aren't getting multiple values out of a single function.
Another big issue is that you are calling get_marks incorrectly. The way you have defined it does not take any argument, so you will run into compilation issues because you are trying to pass it arguments when it does not expect any. You are also not properly passing arguments in the first place. You should not put a datatype before arguments.
Here is a simple rewrite of your program that should get the results you want:
#include <iostream>
using namespace std;
void studentDetails()
{
string name, surName, schoolName;
cout << "Enter your name: \n";
cin >> name;
cout << "Enter your surname: \n";
cin >> surName;
cout << "Enter your school name: \n";
cin >> schoolName;
}
int getMark(const string &class)
{
int english, mathematics, lifeOrientation, history, computerLiteracy, geography;
cout << "Enter your mark for " << class << " \n";
cin >> val;
while (!(val >0 && val <= 100))
{
cout << "Invalid mark \n";
cout << "Please enter your mark for English: \n";
cin >> val;
}
return val
}
float calcAverageYearMark()
{
int english, mathematics, lifeOrientation, history, computerLiteracy, geography;
english = getMark("english");
mathematics = getMark("mathematics");
lifeOrientation = getMark("lifeOrientation");
history = getMark("history");
computerLiteracy = getMark("computerLiteracy");
geography = getMark("geography");
float average = (english + mathematics + lifeOrientation + history + computerLiteracy + geography)/6.0;
return average;
}
int main()
{
studentDetails();
getMarks();
calcAverageYearMark();
return 0;
}
Please note that I have not tested this code and it is more meant to demonstrate a better structure to accomplish what you are trying to do.
I have the following code in which I'm trying to validate the radius. If the radius is zero or negative, I'm supposed to give the user endless opportunities to write the radius again until it's valid. When I tested the code, I wrote a negative value and it worked just fine, it gave me endless opportunities until I gave a valid value, but if I wrote a correct value since the beginning, it made me write the value again as if it was incorrect.
#include <iostream>
#include <stdlib.h>
#include "listaEnlazada.h"
using namespace std;
using namespace listaenlazada;
void menu()
{
cout << "\n\t\tLISTA ENLAZADA SIMPLE\n\n";
cout << "1. Insert at begginig " << endl;
cout << "2. Insert at the end " << endl;
cout << "3. Insert in a specific position " << endl;
cout << "4. Write list " << endl;
cout << "5. Search element " << endl;
cout << "6. Exit " << endl;
}
int main() {
CircPtr cabezaLista = NULL, position;
int op;
string name;
double radius;
double x;
double y;
int pos;
do {
menu();
cin >> op;
switch(op)
{
case 1:
cout << "Write the name of the circle: ";
cin >> name;
cout << "\n Write radius: ";
cin >> radius;
do{
cout << "Invalid input. ";
cin >> radius;
}while(radius <= 0);
cout << "\n Write center: ";
cout << "X: ";
cin >> x;
cout << "Y: ";
cin >> y;
insertarCabeza(cabezaLista, name, radius, x, y);
break;
case 2:
cout << "Write the name of the circle: ";
cin >> name;
cout << "\n Write radius: ";
cin >> radius;
do{
cout << "Invalid input. ";
cin >> radius;
}while(radius <= 0);
cout << "\n Write center: ";
cout << "X: ";
cin >> x;
cout << "Y: ";
cin >> y;
insertarFinal(cabezaLista, name, radius, x, y);
break;
case 3:
cout << "Write the name of the circle: ";
cin >> name;
cout << "\n Write radius: ";
cin >> radius;
do{
cout << "Invalid input. ";
cin >> radius;
}while (radius <= 0);
cout << "\n Write center: ";
cout << "X: ";
cin >> x;
cout << "Y: ";
cin >> y;
cout << "Position : ";
cin >> pos;
posicion = buscarPosicion(cabezaLista, pos-1);
if (posicion != NULL)
insertarPosicion(posicion, name, radius, x, y);
break;
case 4:
cout << "\n\n Showing list : ";
escribirLista(cabezaLista);
break;
case 5:
cout << "\n Center of circle to search: ";
cout << "X: ";
cin >> x;
cout << "Y: ";
cin >> y;
buscarElemento(cabezaLista, x, y);
break;
case 6:
cout << "\n End of the program. ";
break;
}
cout << endl;
}while(op != 6);
return 0;
}
Just use while loop instead of do while loop. In your code because of cin you are taking one input value and for any value which user enters, next do while loop execute ones without checking condition so your prompting with invalid input on the correct radius input.
Instead of this
cout << "\n Write radius: ";
cin >> radius;
do{
cout << "Invalid input. ";
cin >> radius;
}while(radius <= 0);
Do like this
cout << "\n Write radius: ";
cin >> radius;
while(radius <= 0){
cout << "Invalid input. ";
cin >> radius;
}
Learn the basics of the loops.
I am writing a program and it is a long program and I have just started. I just tested it for running, Please tell me why it is not having user input:
#include <iostream>
using namespace std;
struct courses{
int CLO1, CLO2, CLO3, CLO4, CLO5;
int tcounter;
};
int main(){
cin.clear();
courses C1;
C1.CLO1;
C1.CLO2;
C1.CLO3;
int counter = 0;
char name;
cout << "Enter your Name: ";
cin >> name;
cout << "For C1, we have three CLOs that CLO1,CLO2 and CLO3. CLO1 and CLO3 are linked to PLO1 and CLO2 is linked to PLO2 " << endl;
cout << "Enter your marks in CLO1 for C1:(Out of 10) ";
cin >> C1.CLO1;
if (C1.CLO1 >= 5){
counter++;
}
cout << "Enter your marks in CLO2 for C1:(Out of 10) ";
cin >> C1.CLO2;
if (C1.CLO2 >= 5){
counter++;
}
cout << "Enter your marks in CLO3 for C1:(Out of 10) ";
cin >> C1.CLO3;
if (C1.CLO3 >= 5){
counter++;
}
cout << counter;
return 0;
}
As per me the program is fine.
Three things you need to change:
variable type of name from char to string
C1.CLO1;C1.CLO2;C1.CLO3; remove these from your code it doesn't make any sense.
Print the values and check :P
This question already has answers here:
Using getline(cin, s) after cin [duplicate]
(13 answers)
Closed 7 years ago.
I'm relatively new to C++, but not to programming, and I'm confused as to why I am having this very strange issue with a while loop in my C++ program.
while (runUserInputLoop)
{
displayMenu();
cout << "Enter the number that corresponds with your choice from the menu: ";
getline(cin, menuLoopChoice);
if (menuLoopChoice == "1")
{
cout << "Enter mean: ";
cin >> mean;
cout << "Enter z-score: ";
cin >> z;
cout << "Enter standard deviation: ";
cin >> stDev;
cout << "Enter sample size: ";
cin >> n;
oneSampZInt(mean, z, stDev, n);
}
else if (menuLoopChoice == "2")
{
cout << "Enter mean: ";
cin >> mean;
cout << "Enter t-score: ";
cin >> t;
cout << "Enter standard deviation: ";
cin >> stDev;
cout << "Enter sample size: ";
cin >> n;
oneSampTInt(mean, t, stDev, n);
}
else if (menuLoopChoice == "3")
{
cout << "Enter mean for first sample: ";
cin >> mean1;
cout << "Enter mean for second sample: ";
cin >> mean2;
cout << "Enter standard deviation for first sample: ";
cin >> stDev1;
cout << "Enter standard deviation for second sample: ";
cin >> stDev2;
cout << "Enter z-score: ";
cin >> z;
cout << "Enter size of first sample: ";
cin >> n1;
cout << "Enter size of second sample: ";
cin >> n2;
indepMeansZInt(mean1, mean2, stDev2, stDev1, n1, n2, z);
}
else if (menuLoopChoice == "4")
{
cout << "Enter mean for first sample: ";
cin >> mean1;
cout << "Enter mean for second sample: ";
cin >> mean2;
cout << "Enter standard deviation for first sample: ";
cin >> stDev1;
cout << "Enter standard deviation for second sample: ";
cin >> stDev2;
cout << "Enter t-score: ";
cin >> t;
cout << "Enter size of first sample: ";
cin >> n1;
cout << "Enter size of second sample: ";
cin >> n2;
indepMeansTInt(mean1, mean2, stDev2, stDev1, n1, n2, t);
}
else if (menuLoopChoice == "5")
{
cout << "Enter sample proportion: ";
cin >> p;
cout << "Enter sample size: ";
cin >> n;
cout << "Enter z-score";
cin >> z;
onePropZInt(p, n, z);
}
else if (menuLoopChoice == "6")
{
cout << "Enter proportion from sample one: ";
cin >> p1;
cout << "Enter proportion from sample two: ";
cin >> p2;
cout << "Enter size of sample one: ";
cin >> n1;
cout << "Enter size of sample two: ";
cin >> n2;
cout << "Enter z-score";
cin >> z;
twoPropZInt(p1, p2, n1, n2, z);
}
else if (menuLoopChoice == "7")
{
cout << "Enter chi-sqaured right value: ";
cin >> chiSqrdRight;
cout << "Enter chi-sqaured left value: ";
cin >> chiSqrdLeft;
cout << "Enter sample variance: ";
cin >> variance;
cout << "Enter sample size: ";
cin >> n;
chiSqrdInt(chiSqrdRight, chiSqrdLeft, variance, n);
}
else if (menuLoopChoice == "8")
{
cout << "Enter mean of differences: ";
cin >> DBar;
cout << "Enter standard deviation of differences: ";
cin >> SD;
cout << "Enter number of matched pairs: ";
cin >> n;
cout << "Enter t-score: ";
cin >> t;
matchedPairsTInt(DBar, SD, n, t);
}
else if (menuLoopChoice == "A" || menuLoopChoice == "a")
{
cout << "Enter population mean: ";
cin >> mean1;
cout << "Enter sample mean: ";
cin >> mean2;
cout << "Enter population standard deviation: ";
cin >> stDev;
cout << "Enter size of sample: ";
cin >> n;
cout << "Enter z-score: ";
cin >> z;
oneSampZTest(mean1, mean2, stDev, n, z);
}
else if (menuLoopChoice == "B" || menuLoopChoice == "b")
{
cout << "Enter mean of sample one: ";
cin >> mean1;
cout << "Enter mean of sample two: ";
cin >> mean2;
cout << "Enter standard deviation of population one: ";
cin >> stDev1;
cout << "Enter standard deviation of population two: ";
cin >> stDev2;
cout << "Enter size of sample one: ";
cin >> n1;
cout << "Enter size of sample two: ";
cin >> n2;
cout << "Enter z-score: ";
cin >> z;
twoSampZTest(mean1, mean2, stDev1, stDev2, n1, n2, z);
}
else if (menuLoopChoice == "C" || menuLoopChoice == "c")
{
cout << "Enter population mean: ";
cin >> mean1;
cout << "Enter sample mean: ";
cin >> mean2;
cout << "Enter sample standard deviation: ";
cin >> stDev;
cout << "Enter size of sample: ";
cin >> n;
cout << "Enter t-score: ";
cin >> t;
oneSamptTest(mean1, mean2, stDev, n, z);
}
else if (menuLoopChoice == "D" || menuLoopChoice == "d")
{
cout << "Enter mean of sample one: ";
cin >> mean1;
cout << "Enter mean of sample two: ";
cin >> mean2;
cout << "Enter standard deviation of sample one: ";
cin >> stDev1;
cout << "Enter standard deviation of sample two: ";
cin >> stDev2;
cout << "Enter size of sample one: ";
cin >> n1;
cout << "Enter size of sample two: ";
cin >> n2;
cout << "Enter t-score: ";
cin >> t;
twoSamptTest(mean1, mean2, stDev1, stDev2, n1, n2, t);
}
else if (menuLoopChoice == "E" || menuLoopChoice == "e")
{
cout << "Enter the population proportion: ";
cin >> p1;
cout << "Enter the sample proportion: ";
cin >> p2;
cout << "Enter the sample size: ";
cin >> n;
cout << "Enter the z-score: ";
cin >> z;
onePropZTest(p1, p2, n, z);
}
else if (menuLoopChoice == "F" || menuLoopChoice == "f")
{
cout << "Enter sample proportion one: ";
cin >> p1;
cout << "Enter sample proportion two: ";
cin >> p2;
cout << "Enter the x value of proportion one: ";
cin >> x1;
cout << "Enter the x value of proportion two: ";
cin >> x2;
cout << "Enter the size of sample one: ";
cin >> n1;
cout << "Enter the size of sample two: ";
cin >> n2;
cout << "Enter the z-score: ";
cin >> z;
twoPropZTest(p1, p2, x1, x2, n1, n2, z);
}
else if (menuLoopChoice == "q" || menuLoopChoice == "Q")
{
runUserInputLoop = false;
}
}
On the first iteration through the loop, everything works fine. However, on all subsequent iterations, the loop seems to iterate once, without any input, and then again, allowing me to enter input once again. So essentially, there is an extra iteration that causes it to perform this portion of the while loop twice:
displayMenu();
cout << "Enter the number that corresponds with your choice from the menu: ";
getline(cin, menuLoopChoice);
Here is a picture of how it looks in the console: . The crudely circled portion is the "ghost iteration." I feel like it should be something simple, but I'm not extremely familiar with C++ yet, so I'm stumped. The full code for the program is available here if necessary.
std::istream::operator>> reads characters from the stream until it encounters whitespace (such as an end-of-line character), but it leaves the whitespace character in the stream, so the next read will see it. That's fine if the next read is an operator>>, since it will skip over leading whitespace, but std::getline() just reads until it sees the delimiter character ('\n' by default). Since the previous call to operator>> left a '\n' as the next character in the stream, std::getline() sees it, and returns immediately. To get around this, you can call std::cin.ignore() at the end of your loop to discard the '\n' that's been left in the input stream.
#include <iostream>
#include <iomanip>
using namespace std;
class Rectangle
{
float x, y;
public:
void value (float,float);
float area () {return (x*y);}
};
void Rectangle::value (float a,float b)
{
x = a;
y = b;
}
class Circle
{
float x;
public:
void value (float);
float area () {return (3.14*x*x);}
};
void Circle::value (float a)
{
x = a;
}
int main ()
{
float q,a,b;
char reply;
cout << "\t\tArea Calculator";
do
{
cout << "\n\nPlease select from the following: ";
cout << "\n1. Rectangle";
cout << "\n2. Cirlce";
cout << "\n3. Exit";
cout << "\n\n";
cin >> q;
if (q==3)
break;
if (q==1)
{
system("cls");
Rectangle rect;
cout << "\nPlease enter length: ";
cin >> a;
cout << "\nPlease enter width: ";
cin >> b;
cout << "\nArea: " << rect.area();
cin.get();
cout << "\n\nDo you want to continue y/n: ";
cin >> reply;
if (toupper(reply) == 'N')
{
cout << "\n\n";
cout << "Goodbye!";
break;
}
}
if (q==2)
{
system("cls");
Circle circ;
cout << "\nPlease enter radius: ";
cin >> a;
cout << "\nArea: " << circ.area();
cin.get();
cout << "\n\nDo you want to continue y/n: ";
cin >> reply;
if (toupper(reply) == 'N')
{
cout << "\n\n";
cout << "Goodbye!";
break;
}
}
} while (toupper(reply!='Y'));
{
cout << "\n\n";
system("pause");
}
}
The code above, debugs with the following warning:
"warning C4244: 'return' : conversion from double to float, possible loss of data"
... I am pretty sure this is the reason for the mis-calculations when the code is run (for e.g. it returns the area of a 5x5 square as 1.15292e+016) - Please will anyone explain the correct method for resolving this, I can't seem to get my rather-dopey-head around it :(
The wrong result is not a result of double to float conversion but rather a result of not initializing the dimensions members of the Rectangle/Circle objects.
You need to call rect.value(a,b) after reading the values from the user.
Not doing this leaves the object's x and y members uninitialized, therefore containing some arbitrary values - leading to wrong result of the calculation.
Same goes for calling circ.value(a) for the circle.
cout << "\nPlease enter length: ";
cin >> a;
cout << "\nPlease enter width: ";
cin >> b;
rect.value(a,b);
cout << "\nArea: " << rect.area();
The warning on double to float conversion is probably the result of the "cin >> b" style lines. The cin stream >> operator handles reading double, not floats.
When you attempt to read from cin into a float, you first get a double value which is then implicitly cast to float. As float has lesser accuracy than double, the compiler warns you that you may lose precision doing this. Assuming float accuracy is enough - this poses no problem. You can solve this simply by declaring the classes and variable to use double instead of float.
You're not initializing the data members of the class
rect.area(); and circ.area(); are calculating area on some garbage values
Use constructors:
Rectangle(float a, float b):x(a),y(b){}
Circle(float a):x(a){}
Then
cin >> a;
cin >> b;
Rectangle rect(a,b);
rect.area();
and
cin >> a;
Circle circ(a);
circ.area();