Why won't this nested switch statement work? (C++) [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 8 years ago.
Improve this question
I'm having issues with this program. I'm trying to use a nested switch statement.
void main()
{
int function_select, log_select, root_select ;
do
{
cout << "Please select the function you would like to use \n 1 : Logarithm \n 2 : Root \n 0 : Quit" << endl;
cin >> function_select;
switch (function_select)// main menu
{
case 1:// log menu
{
cout << "Please select which logarithm function you would like to perform \n 1 : Common Log \n 2 : Natural Log \n 3 : Log Base n \n 0 : Back" << endl;
switch (log_select)
{
case 1://common log
{
}
break;
Sorry if it looks a little messy. I'm still pretty new to C++. There is more to this program, but i know the problem is in this section. When i run the program, i get an error stating that the variable log_select is being used without being initialized, even though I initialized it in the main program. Any suggestions that could fix this? And if you could explain why this doesn't work, I'd appreciate it.

You clearly don't initialize log_select, and you don't read any user input to it, either.
That's why you get an error: its value is unspecified (read: non-existent) and your attempt to evaluate it has undefined behaviour (read: don't do this).
I guess you forgot:
cin >> log_select;
To initialise those variables to 0, you'd write:
int function_select = 0, log_select = 0, root_select = 0;
…though if you'd done that then you wouldn't have had a compiler error informing you about this bug! Sometimes failing to initialise variables is useful.

You don't read input into log_select before the switch statement which uses it.

"Initialized" is different from "declared". You clearly declared that variable, but you didn't assign a value to it. Therefore you didn't initialize it.

Related

Why is it when I add an integer variable to my class function, it produces an 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 1 year ago.
Improve this question
I'm trying to add a variable of type int to my class function, but when I do, it produces an error:
C6001 Using uninitialized memory 'vYear'
(it states this for all integer variables)
It specified I need to initialize the variable, but I want it to be initialized by the user. When I click the hint to tell me a possible fix, it specifies to initialize the variable as int vYear{} which as a result, adds a value of 0 when I run the program.
Any assistance would be appreciated.
You need to read in the values for the variables BEFORE you then print them out, ie change this:
cout << "Vehicle Color: " << vColor;
cin >> vColor;
To this instead:
cin >> vColor;
cout << "Vehicle Color: " << vColor
And so on for all of the variables.

How to call my function within parameters in my class (C++) [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 5 years ago.
Improve this question
Hello I'm wondering how I can call functions within parameters in my class in main?
class processChoice {
public:
void processInput(string, int, string, int);
};
void processChoice::processInput(string processInput_UN,
int processInput_PC,
string initial_UN,
int initial_PC) {
for (; (processInput_UN != initial_UN) || (processInput_PC != initial_PC);
cout << endl) {
cout << "Enter your username: " << flush;
cin >> initial_UN;
cout << "Enter your 4 digit pincode: " << flush;
cin >> initial_PC;
cout << endl;
if ((processInput_UN == initial_UN) && (processInput_PC == initial_PC)) {
cout << "Access granted!" << endl;
} else {
cout << "Username and/or pincode doesn't match, try again..."
<< endl;
}
}
int main() {
userPinchoice Choice;
Choice.chooseUsername();
Choice.choosePincode();
cout << endl;
initial Values;
Values.initialUsername();
Values.initialPincode();
processChoice Input;
Input.processInput();
return 0;
What am I suppose to put in the round brackets at Input.processInput()?
I have been trying to get it to work but I just can't seem to access the function. I'm new to this so any help would be welcome.
Thanks in advance!
The bulk of your problem lies in the class processChoice. Here are some of such errors:
Firstly, the parameters specified in the function declaration in your class is faulty:
void processInput(string, int, string, int);
Here, you have only specified 4 data types, not variables. Kee in mind, these are variables that store the data that is passed from another function. In order to do this, you need to have these variables declared in the above line, variables with specific names that can be identified inside a function. You should have this line in your function declaration:
void processChoice::processInput(string processInput_UN, int processInput_PC, string initial_UN, int initial_PC)
This brings up another problem. Your function header is diffent upon declaration, and its header is different upon defining. The compiler sees it as 2 different functions. Therefore, you should keep your function headeer the same when declaring it and defining it.
Secondly, the for-loop inside your function has syntax errors:
for (; (processInput_UN != initial_UN) || (processInput_PC != initial_PC);
cout << endl) {
Firstly, judging from the syntax of the condition statement of the loop, it should be a do-while loop, not a for loop. Secondly, the cout << endl; should not be inside the condition statement of the for-loop; it should be implemented with the rest of the function. Thirdly, you do not put a semicolon at the end of your condition statement; it tells the compiler that this an empty loop without a body. Your loop should be something like:
do
{
cout << endl; // this is where you put the cout statement
// add rest of function code here
}
while ((processInput_UN != initial_UN) || (processInput_PC != initial_PC))
Another side note, why do you need 4 input parameters in your function? You take the pin number and username as input from the user, eliminating the need for 2 parameters. Something like:
string initial_UN;
int initial_PC;
If you declare this inside your function, just before the do-while loop I suggested above, then that eliminates these 2 variables from being parameters.
Now, to get to your question, if we have the following declaration:
Input.processInput();
Then we need to pass 4 parameters (2 if you follow my notes above) to it, and that is what the brackets next to the function name in this line of code a for. To pass a value to the function, simply, do the following (I'm only passing 2 parameters here, you can pass how many ever parameters you have defined in yout class only, not less or not more):
Input.processInput("Username", "password");
There are 2 input parameters that specify what the username and password should be. To differentiate the parameters being passed, syntax requires a comma to split them. You can also pass variables as arguments; however, make sure that you have initialized these variables.
This is a long post, so I may have made some errors I didn't notice. If there is any other mistake I noticed, then please inform me in the comments.
Good luck!

How to write an if-else 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 6 years ago.
Improve this question
I am very new to C++. My objective is to write the following logic:
if a = yes then print "ok", else return 0
Here is my code so far:
int a;
cin>>a;
if (a = "Yes") { // Error right here
cout<< "ok"; << endl;
}else{
return 0;
}
First of all, what do you want your program to do?
You need to distinguish assignment and equal to operator.
Please note that you need to understand the basics before proceeding to perform conditional statements.
A reasonable program should go like this:
int a;
cin>>a;
if (a == 5) { // 5 is an integer
cout<< "You entered 5!" << endl; // no semicolon after "
}
return 0; // must be out of the else statement
= assigns things.
Use == to compare, however you are comparing an int with a string.
If you are not careful, you compare the address of a char * with a number when dealing with strings.
Use a std::string instead.
#include <string>
//.... some context I presume
std::string a;
cin >> a;
if (a == "Yes") { // Error right here
cout<< "ok"; << endl;
}else{
return 0;
}
There are multiple errors in this code.
You need to use the comparison operator in your condition. This is denoted by the double equal sign "==". Your code is using assignment "=" which tries to assign the value "Yes" to the variable a. This is a common error in C/C++ so you need to be careful whenever you compare things.
The other error is that you have declared the variable a to be an integer, so you will get a type mismatch error when you try to compile because "Yes" is a string.
Your code is incorrect in terms of data types. You have a variable 'a' of type int which you are comparing to string "yes". Try to see it from a logical point of view; you can compare:
2 numbers (for example, 2 is greater than 1)
2 strings (for example, "food" is not the same word as "cat")
Etc...
In your case, you are comparing a number inputted(let's assume 5) to a word "yes". When you try to input a letter for var a, you will get a compilation error. Therefore, simply change the following:
string a;
Another problem with your code is when the if-then loop checks the condition; a comparison operator is 2 equal signs next to each other instead of a single equal sign. A single equal sign assigns the item on the right to the item on the left. For example, in:
int num = 5;
The variable num is assigned 5. But you want to make a comparison, not assign the variable its own condition!
Your loop is always true because you set the variable to the condition it is supposed to meet. You also need to do the following:
if (a == "yes")
This compares the value stored in var a to the value on the right side of the == .
Just some advice, I would recommend you to get some good books on c++. Search them online. You can also take online programming courses on edx, course record, etc... . There are a lot of other free learning resources online too which you can make use of. You may also want to dive into a simpler programming language; I would recommend scratch. It gives you a very basic idea about programming and can be done in less than a week.
** Note that I feel this is the simplest way; however, you can also set type of a to a char, accept input and then convert it back to a string. Good luck!

How does pointer in function work at this code? [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 6 years ago.
Improve this question
int f_point(int kek,int *lol) {
*lol *= *lol;
return kek;
}
int main {
int x;
std::cin >> x;
int *adress_of_x = &x;
int a,b = f_point(x,&x); //how does it work?
std::cout << a << LINE_JUMP;
std::cout << b << LINE_JUMP;
}
For example, if I give 2 to program then I will get 0 and 2. Why?
b = f_point(x,&x) in this statement value of first parameter is 2.
Your function is not changing the value of first parameter and returns the same value.
Your are passing first parameter by value so it has no relation with the updated value of x. Variable a is uninitialized, so it is taking a garbage value.
int a,b = f_point(x,&x); //how does it work?
The variable declaration leaves a uninitialized and initializes b from the result of f_point(x,&x);.
Since it's an uninitialized variable, accessing the value of a in the
std::cout << a << LINE_JUMP;
statement leads to undefined behavior of your program. Having an output of 0 is just one of any possibilities (including your fridge explodes unexpectedly or little demons flying out of your nostrils).

Compilation error: More than one instance of overloaded function matches the arument list [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 6 years ago.
Improve this question
I have an assignment for school:
i. Create a classical Guitar object with price $150 and type = “classical”. Set the new price to $100 and display all the information about the Guitar object.
ii. Create an electric Guitar object with price $135 and type = “electric”. Change the price as there is a promotion and display all the information about the Guitar object.
I am trying to solve it on my own, but I am new in C++ and I'm stuck with compiler errors that I can't understand.
Here the class that I have created in my Guitar.h file.
#pragma once
#include<iostream>
#include <string>
#include<sstream>
using namespace std;
class Guitar
{
private:
string type;
double price;
public:
Guitar(string type, double price);
string getType();
double getPrice();
void setPrice(double newPrice);
void setPrice(bool promotion);
string toString();
};
This is the class implementation in my Guitar.cpp file
#include "Guitar.h"
Guitar::Guitar(string typeclass, double priceclass)
{
type = typeclass;
price = priceclass;
}
string Guitar::getType()
{
return type;
}
double Guitar::getPrice()
{
return price;
}
void Guitar::setPrice(double newPriceclass)
{
price = newPriceclass;
}
void Guitar::setPrice(bool promotion)
{
if (promotion == true)
price *= 0.9;
}
string Guitar::toString()
{
stringstream info;
info << "Guitar Type: " << type << endl
<< "Price: " << price << endl;
return info.str();
}
Finally I have my main file GuitarApp.cpp
#include"Guitar.h"
int main()
{
Guitar guitar1("Classical", 150.0);
guitar1.setPrice(100) << endl;
cout << guitar1.toString() << endl;
Guitar guitar2("Electrical", 135.0);
guitar2.setPrice(true);
cout << guitar2.toString() << endl;
}
I have 2 errors:
more than one instance of overloaded function Guitar::setPrice matches the argument list
Guitar::setPrice ambiguous call to overloaded function.
Can someone explain to me the errors and what I should do to get the code compiled?
Edit: After having changed 100 to 100.0, I got 4 more errors:
mismatch in formal parameter list
expression must have integral or unscoped enum type
cannot determine which instance of function template std::endl; is intended
'<<': unable to resolve function overload
All errors are on line 7 of my GuitarApp.cpp which is
guitar1.setprice(100.0)<<endl;
If i were to edit the price of the guitar from 100.0 back to 100, I would get the two error that I initially had.
The type of the literal 100 is int. Since int is just as easily convertible to bool as it is to double, it's ambiguous which of those functions should be called.
Changing 100 to 100.0 (a double literal) should fix this.
Normally we did not fix home works here. It is better to ask "Why this line of code did not work" instead of throwing a bunch of homeworks here in the hope to get it made ready from others...
Please also get in mind that your question is "Off topic" because:
Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers.
OK, your code have following syntax bugs:
guitar1.setPrice(100.) ; // see the "." behind the number!
You have to methods:
void setPrice(double newPrice);
void setPrice(bool promotion);
And you wrote:
guitar1.setPrice(100)
100 is an int and not a double and not a bool. So the compiler can not decide to make from your 100 a bool which has value true or make it a double with value 100.. So simply add a dot to make your value a floating point one which your compiler takes as double.
Next bug:
cout << guitar2.toString() << endl; // see the "2" behind guitar !
Only a typo...
Some remarks:
Splitting such a class in a header and a source file is bad! The optimizer has no chance to inline the functions.
Using using namespace std; can be bad! It is much better to write std::string and all you need to see from which namespace your definition comes. That makes a bit more work but is much better to read later, especially if you use multiple namespaces from multiple libraries.
Explanation:
It is easy to save typing some characters at a first view. But if you later (re-)use your code in an bigger application where you have to deal with a lot of libraries which may define functions/classes/what ever with the same name as one of the other library do, you start changing your code.
A simple example is to have posix read and istream read in place. Here it is also a good idea to give a '::read' to select the posix one which is not bound to a namespace.
Is it dogmatic to give the hint to not use using namespace? My personal experience is simply that if you use it, you may run into problems if your code is (re-)used later in bigger applications. And for me it is mandatory to write my code as such, which can be (re-)used without problems and or a lot of adoptions/corrections in future.
You have to decide: Save some characters to type today and may run into trouble later or do the job right now.
Maybe for the homeworks code is ok to do so. But I believe it is a good point to talk about the problems which may arise on that kind of code writing.