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!
Related
I am attempting to recreate some "R" scripts in C++, just for the fun of it. Have used C decades ago but not recently. Now what I have is a bit of code where I am reading data from a binary file and placing the data into a structure (or class) with an unknown number of array structures (for the file reading side). Not knowing exactly how many arrays are needed, I define the number after reading another binary file which contains that data. So, I have two options; one to enter new data (which saves that plus the number of arrays to two files); another to read saved data back in (which provides the number of needed array structures). Having done either option via 'IF' conditionals, I need the new or recovered data to perform math on outside those conditionals. This is where things go wrong. The data is not available. The simple example recreates the problem and I have not stumbled upon the solution yet. I am not familiar enough with C++ to find what is most likely something simple to fix. The 'closed' function's first line outside the 'if' conditionals does work as expected, but that's not the data I need, and I don't want that line in the program.
#include <iostream>
using namespace std;
void closed(void);
class traverse {
public:
int sta;
};
int main()
{
closed();
return 0;
}
void closed(void)
{
traverse stations[1]; // removes 'stations was not declared' error on line 35.
cout << "Enter 1 or 2\nSelect: ";
int selType;
cin >> selType;
if (selType == 2) {
cout << selType << " selected\n";
traverse stations[1];
stations[0].sta = 2; //need this member value available outside conditional.
cout << "Value is " << stations[0].sta << " inside." << endl;
} else {
cout << selType << " selected\n";
traverse stations[1];
stations[0].sta = 1; //need this member value available outside conditional.
cout << "Value is " << stations[0].sta << " inside." << endl;
}
cout << "Value is " << stations[0].sta << " outside." << endl;
}
I originally used a 'struct' but decided to try a 'class' to discover the differences. But, the same problem persists with both, so I don't think it is anything with the definitions, but perhaps with different declarations. Any ideas would be greatly appreciated. Thanks.
If you need it to live longer than the scope of the if, then declare it in the outer scope where you need it to continue living.
After you added this line to deal with the warning:
traverse stations[1]; // removes 'stations was not declared' error on line 35.
You left the declaration of stations inside the if. That hides the outer name, and will receive the data, then go out of scope when the brace-enclosed block exits. To put data into the outer stations don't hide it.
If you need this data to live longer than the function call itself, you'll need to pass in an object to be written into, or allocate and return one to the caller. Perhaps a vector? I don't like (or recommend) to pass raw arrays because they decay to pointers and lose the bounds encoding from their type. That makes it too easy to go out of bounds without being very careful. There are smart pointer wrappers you could use, or a span class, etc., to help do it more sensibly.
This question already has answers here:
c++ change function's variable argument
(2 answers)
Closed 2 years ago.
I created a function which takes a string for a message and an input value (primarily an integer, at least in this case) so I can print a message and take an input in a single function instead of two lines of code. Here is the snippet:
main.h
void input(std::string msg, int choice) {
std::cout << msg;
std::cin >> choice;
}
However, when passing the function in my main function, it doesn't perform the same way this would:
main.cpp (working code with expected result)
int initial_choice;
std::cout << "Invalid input provided. Please try again: ";
std::cin >> initial_choice;
main.cpp (working code with unexpected result)
int initial_choice;
input("Invalid input provided. Please try again: ", initial_choice);
When it comes to the snippet with the expected result, my switch case function properly detects the input (in this case it is initial_choice) as a valid integer. For example, entering 1, 2, or 3 will work with case 1:, case 2:, and case 3:. However, the snippet with the unexpected result doesn't detect any of the three valid numbers in my switch case function, instead they all run the code under the default case.
This has nothing to do with cin, cout, switch statements, etc.
As user202729 has pointed out, it is a simple matter of function parameter-passing.
C++ is not Fortran III; by default, parameters to functions are passed by value, not by reference. This means that if within a function you change the value of one of its parameters, this change will only be in effect within the function; the change will not be reflected to the caller.
So, your std::cin >> choice; statement works perfectly well, and it stores the value entered by the user in your choice variable. However, this value forever ceases to exist once the function ends, and it is never reflected back to the caller, which in this case is the initial_choice variable of your main() method.
To fix this, you have two options:
Pass the variable by reference, so that the function can modify it.
Do not pass the variable at all; instead, have the function return the value; that's generally what functions are for.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Write a function NumberOfPennies() that returns the total number of pennies given a number of dollars and (optionally) a number of pennies. Ex: 5 dollars and 6 pennies returns 506.
For the above question, here is the code below.
Getting an error: error: no matching function for call to 'NumberOfPennies(int)'
#include <iostream>
using namespace std;
int NumberOfPennies(int one,int two)
{
return (one*100+two);
}
int main() {
cout << NumberOfPennies(5, 6) << endl; // Should print 506
cout << NumberOfPennies(4) << endl; // Should print 400
return 0;
}
However, when I put int two=0 in the function NumberOfPennies it is working. Why is this so? Can anyone please explain this.
#include <iostream>
using namespace std;
int NumberOfPennies(int one,int two=0)
{
return (one*100+two);
}
int main() {
cout << NumberOfPennies(5, 6) << endl; // Should print 506
cout << NumberOfPennies(4) << endl; // Should print 400
return 0;
}
The fact that you have written int two = 0 in the second snippet is your supporting a default value of that parameter two of 0.
This means that it can be omitted at the calling site with the default value assumed if it is, so
cout << NumberOfPennies(4) << endl;
and
cout << NumberOfPennies(4, 0) << endl;
are equivalent. If you don't code your function to support a default value then you need to use two arguments to call NumberOfPennies.
(In order to improve readability consider renaming your parameters one and two to dollars and cents respectively).
There is a concept called default parameter in C++. Look up this link https://www.programiz.com/cpp-programming/default-argument.
In the first case, it is not able to resolve the function call to any existing function call taking just one integer parameter and fails.
int NumberOfPennies(int one,int two).
In the second case, int NumberOfPennies(int one,int two=0) as we have mentioned that if the second integer is not passed assume a default value of 0.During the first run compiler is not able to find a function that takes just one integer parameter. Next, it looks for possible cases where you have a function with 2 integer inputs with one of them having a default value. Your function matches this case and hence compilation is successful.
(Additional info: Its good to write function names and arguments that are intutive. Suggest you to rename arguments as int NumberOfPennies(int dollars,int cents))
"I ran the code below but it is not working"
is not a useful description of your problem.
Why is this so? Can anyone please explain this.
Your problem is clearly described in the compiler error report, which you should include in your post.
error: no matching function for call to ‘NumberOfPennies(int)’
std::cout << NumberOfPennies(4) << std::endl;
^
note: candidate: int NumberOfPennies(int, int)
int NumberOfPennies(int one, int two)
^~~~~~~~~~~~~~~
note: candidate expects 2 arguments, 1 provided
Thus, you tried to invoke the function with 1 argument, when your declaration requires 2.
By adding the default value for the second parameter,
int NumberOfPennies(int one,int two=0) ...
You have provided a value for the second parameter when not provided.
Review default function parameter.
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!
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.