Too many arguments to function - c++

I am getting this error from my header file: too many arguments to function void printCandidateReport();. I am fairly new to C++ and just need some guidance in the right direction to solving this error.
My header file looks like this:
#ifndef CANDIDATE_H_INCLUDED
#define CANDIDATE_H_INCLUDED
// Max # of candidates permitted by this program
const int maxCandidates = 10;
// How many candidates in the national election?
int nCandidates;
// How many candidates in the primary for the state being processed
int nCandidatesInPrimary;
// Names of the candidates participating in this state's primary
extern std::string candidate[maxCandidates];
// Names of all candidates participating in the national election
std::string candidateNames[maxCandidates];
// How many votes wone by each candiate in this state's primary
int votesForCandidate[maxCandidates];
void readCandidates ();
void printCandidateReport ();
int findCandidate();
#endif
and the file calling this header file:
#include <iostream>
#include "candidate.h"
/**
* Find the candidate with the indicated name. Returns the array index
* for the candidate if found, nCandidates if it cannot be found.
*/
int findCandidate(std::string name) {
int result = nCandidates;
for (int i = 0; i < nCandidates && result == nCandidates; ++i)
if (candidateNames[i] == name)
result = i;
return result;
}
/**
* Print the report line for the indicated candidate
*/
void printCandidateReport(int candidateNum) {
int requiredToWin = (2 * totalDelegates + 2) / 3; // Note: the +2 rounds up
if (delegatesWon[candidateNum] >= requiredToWin)
cout << "* ";
else
cout << " ";
cout << delegatesWon[candidateNum] << " " << candidateNames[candidateNum]
<< endl;
}
/**
* read the list of candidate names, initializing their delegate counts to 0.
*/
void readCandidates() {
cin >> nCandidates;
string line;
getline(cin, line);
for (int i = 0; i < nCandidates; ++i) {
getline(cin, candidateNames[i]);
delegatesWon[i] = 0;
}
}
why am I getting this error and how can I fix it?

On the header file you declare:
void printCandidateReport ();
But on the implementation is:
void printCandidateReport(int candidateNum){...}
Change the header file to
void printCandidateReport(int candidateNum);

The error message is telling you precisely what the problem is.
In your header file you declare the function with no parameters:
void printCandidateReport ();
In the source file you define it with a parameter of type int:
void printCandidateReport(int candidateNum){
Either add the missing parameter to the declaration, or remove it from the definition.

The error too many arguments to function can be fixed by eliminating the excess arguments
(parameters) in the function .
This error occurred because your header file has no parameter values, and in the actual source code you use the int parameter.
You have two choices, you can add the missing int parameter in the function declaration, or remove it entirely from the function.

The header file declares the function printCandidateReport() with no parameters and the cpp file defines the function with an int parameter. Just add the int parameter to the function declaration in the header file to fix it

Related

I keep returning the same value for variable howMany

I have a file that has been previously filled with data. The file consists of an array of structures. Each structure represents a round and each array position represents up to 20 rounds for an individual. My .h file:
define READTWENTY_H
class readTwenty {
public:
readTwenty();
void nonZeroes(int, int &);
struct a_round {
int score;
double course_rating;
int slope;
char date[15];
char place[40];
char mark[1];
}; //end structure definition
struct a_round all_info[20];
FILE *fptr;
}; //end class
#endif
In the data file some "rounds" have actual data in them and some have previously been filled with zeroes. I want to count the zero rounds. I have a loop in which I can ask for another "person" value to look at. This value is sent to a function in which the number of zero rounds is determined and returned by reference to a variable named "howMany".
// readMember.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "readTwenty.h"
using namespace std;
int main()
{
int person = 0;
readTwenty personData;
int howMany = 0;
while (person != -999) {
cout << "Which member (keyfield) would you like to see? -999 to stop ";
cin >> person;
if (person == -999)
exit(0);
personData.nonZeroes(person-1, howMany);
cout << "The number of non-zero values for this member is " << howMany << endl;
}//end while
return 0;
}
Once sent to the nonzeroes function as "key" I create an offset into the file and read the 20 rounds for that individual and return by reference the value of count back to the calling routine into variable howMany.
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include "readTwenty.h"
#include <errno.h>
#include <cstdio>
readTwenty::readTwenty() {
const char *configfile;
configfile = "scores.dat";
#ifdef WIN32
errno_t err;
if((err = fopen_s(&fptr,configfile, "rb")) != 0)
#else
if ((fp_config = fopen(configfile, "rb")) == NULL)
#endif
fprintf(stderr, "Cannot open cinfig file %s!\n", configfile);
}//end constructor
void readTwenty::nonZeroes(int key, int &count) {
int zeroes = 0;
int offset = key * ((sizeof(all_info[0]) * 20));
fseek(fptr, offset, SEEK_SET);
for (int i = 0; i < 20; i++){
fread(&all_info[i], sizeof(all_info[0]), 1, fptr);
if (all_info[i].score == 0)
zeroes++;
all_info[i].mark[0] = ' ';
}//end for loop
count = 20 - zeroes;
fclose(fptr);
}//end of function nonZeroes
The problem is that the first value that I give for person comes back with the correct number of non-zero rounds. However, each succeeding iteration of the while loop regardless of the second value I give for person comes back with the same result as the first person? Would greatly appreciate any ideas you may have.
I currently have no computer to verify, but one line jumps out to me as it is a common error (for me at least):
The first param to your fread is &all_info[i]; you probably want &(all_info[i]), but this is not how the compiler understands it - & is stronger than [i], so you get (&all_info)[i].
You could also use all_info+i for the same effect.

access private member variable through private member, same class

// M9P369.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
const int MaxSize = 100;
using namespace std;
class Set {
int len; // number of members
char members[MaxSize]; // the set is stored in this array
int find(char ch); // find an element
public:
Set() { len = 0; } // constructor to make a null set initially
int getLength() { return len; } // return number of elements in the set
void showset(); // display the set
bool isMember(char ch); // check for membership
Set operator+(char ch); // overload operator to add an element to the set
Set operator-(char ch); // overload operator to remove an element from the set
Set operator+(Set ob2); // set Union - overloaded by the different type from above overload+ function
Set operator-(Set ob2); // set difference same as above.
};
// Return the index of the element passed in, or -1 if nothing found.
int Set::find(char ch) {
int i;
for (i=0; i < len; i++)
if (members.[i] == ch) return i;
return -1;
}
// Show the set
void Set::showset() {
cout << "{ ";
for (int i=0; i<len; i++)
cout << members[i] << " ";
cout << "}\n";
}
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
I am learning operator overloading, and came across a class access problem.
The line
if (members.[i] == ch) return i;
Gives a tooltip error 'expression must have class type', and compile errors:
\m9p369.cpp(34): error C2059: syntax error : '['
\m9p369.cpp(40): error C2228: left of '.showset' must have class/struct/union
\m9p369.cpp(41): error C2228: left of '.cout' must have class/struct/union
I am defining the private member function find() of class Set, and I get the error upon trying to access the private member char array of the same class, members. Error seems to say I should specify which class it's referring to, why? I already specify the class in the definition:
int Set::find(char ch) {
As I understand, members should be in the scope of the function definition. I looked hard for any stray characters I couldn't find anything odd, all parenthesis seem to match.
Problem is here:
members.[i]
It should be just
members[i]
Remeove the . from
if (members.[i] == ch) return i;
~~~~~~~~~~~^

Parenthesis after variable name C++

Working with the below source code (it is open source) and I've never seen parenthesis after a variable name. UDefEnergyH is definitely a variable as can be seen in line 1. Can anyone tell me what these parenthesis are doing? Don't really know how to Google this. Thanks.
bins[0] = UDefEnergyH.GetLowEdgeEnergy(size_t(0));
vals[0] = UDefEnergyH(size_t(0)); //Don't know what this does???
sum = vals[0];
for (ii = 1; ii < maxbin; ii++) {
bins[ii] = UDefEnergyH.GetLowEdgeEnergy(size_t(ii));
vals[ii] = UDefEnergyH(size_t(ii)) + vals[ii - 1];
sum = sum + UDefEnergyH(size_t(ii));
}
And it is declared here in the header file:
G4PhysicsOrderedFreeVector UDefEnergyH;
It appears operator() is overloaded for the tyupe of UDefEnerfyH.
One way to do this is this solution
#include <iostream>
using namespace std;
struct MJ {
void GetLowEdgeEnergy(size_t arg) {
cout << "GetLowEdgeEnergy, arg = " << arg << endl;
}
void operator ()(size_t arg) {
cout << "operator (), arg = " << arg << endl;
}
};
int main() {
MJ UDefEnergyH;
UDefEnergyH.GetLowEdgeEnergy(42);
UDefEnergyH(42);
return 0;
}
It seems you are referring to the field in the class G4SPSEneDistribution. Its type is G4PhysicsOrderedFreeVector. And have a look at its members here. As you can see there is operator() overloaded and apparently this is what is called on the second line. It is not very easy to find out what that does, but if you have a look at the comment in the header file for G4PhysicsVector, you will see:
00100 // Returns simply the value in the bin specified by 'binNumber'
00101 // of the dataVector. The boundary check will not be Done. If
00102 // you want this check, use the operator [].
This is what is known as direct initialization, in which it first constructs the object with '0' as an immediate parameter, and then assigns it to the first index of the vals array.

Issue With My School Assignment on Classes

So I have an assignment due in my C++ class on classes, and I'm having some trouble. Here is the description of the assignment:
Programming Challenge 7 on page 499 of your text asks you to design and Inventory Class that can hold information for an item in a retail store's inventory. You are given the code for the creation of the class along with code for the implementation of the functions. Demonstrate the class by writing a simple program that uses it. This program should demonstrate that each function works correctly. Submit your .cpp file using the link provided.
And here are the contents of the file sent (it's quite lengthy):
// Chapter 7---Files for Programming Challenge 13---Inventory Class
// This is the inventory.h file.
// It contains the Inventory class declaration.
#ifndef INVENTORY_H
#define INVENTORY_H
class Inventory
{
private:
int itemNumber;
int quantity;
double cost;
double totalCost;
public:
// Default constructor
Inventory()
{ itemNumber = quantity = cost = totalCost = 0; }
// Overloaded constructor
Inventory(int, int, double); // Defined in Inventory.cpp
// Mutators (i.e., "set" functions) defined in Inventory.cpp
void setItemNumber(int);
void setQuantity(int);
void setCost(double);
// setTotalCost calculates the total cost
// and stores the result in the totalCost member
void setTotalCost()
{ totalCost = cost * quantity; }
// Accessors (i.e., "get" functions)
int getItemNumber()
{ return itemNumber; }
int getQuantity()
{ return quantity; }
double getCost()
{ return cost; }
double getTotalCost()
{ return totalCost; }
// Input validation functions
bool validInt(int);
bool validFloat(double);
};
#endif
// This is the inventory.cpp file.
// It contains the Inventory class function definitions.
#include <iostream>
#include "Inventory.h"
using namespace std;
//************************************************************
// Overloaded constructor
// Accepts arguments to be stored in each member variable.
//************************************************************
Inventory::Inventory(int in, int q, double c)
{
setItemNumber(in);
setQuantity(q);
setCost(c);
setTotalCost();
}
//************************************************************
// setItemNumber accepts an argument to be stored in item number.
//************************************************************
void Inventory::setItemNumber(int in)
{
while (!validInt(in))
{
cout << "Item Number must be positive. Please re-enter: ";
cin >> in;
}
itemNumber = in;
}
//************************************************************
// setQuantity accepts an argument to be stored in quantity.
//************************************************************
void Inventory::setQuantity(int q)
{
while (!validInt(q))
{
cout << "Quantity must be positive. Please re-enter: ";
cin >> q;
}
quantity = q;
}
//************************************************************
// setCost accepts an argument to be stored in cost.
//************************************************************
void Inventory::setCost(double c)
{
while (!validInt(c))
{
cout << "Cost must be positive. Please re-enter: ";
cin >> c;
}
cost = c;
}
//************************************************************
// The validInt member tests its integer argument to see
// if it is negative. If the argument is negative, the function
// returns false. Otherwise, the function returns true.
//************************************************************
bool Inventory::validInt(int value)
{
if (value < 0) // the value is negative so it is NOT valid
return false;
else // the integer value is valid
return true;
}
//************************************************************
// The validFloat member tests its floating-point argument to see
// if it is negative. If the argument is negative, the function
// returns false. Otherwise, the function returns true.
//************************************************************
bool Inventory::validFloat(double value)
{
if (value < 0) // the value is negative so it is NOT valid
return false;
else // the floating-point value is valid
return true;
}
I'm just not sure how to use this information to make a program that demonstrates the class, and it could be as simple as me not saving the file the correct way
Just write a main function which instantiates an Inventory object and calls each of its methods in a meaningful way. This isn't a puzzle, just find a way to call the functions that makes sense to you.

Same variable for different datatypes?

I have to call one simple functions with different datatypes in c++. eg,
void Test(enum value)
{
int x;
float y; // etc
if(value == INT)
{
// do some operation on x
}
else if(value == float)
{
// do SAME operation on y
}
else if(value == short)
{
// AGAIN SAME operation on short variable
}
.
.
.
}
Thus I want to eliminate the repetitive code for different datatypes ...
So , I tried to use macro ,depending on values of enum, to define same variable for different datatypes .. but then not able to differentiate between the MACROS
e.g.
void Test(enum value)
{
#if INT
typedef int datatype;
#elif FLOAT
typedef float datatype;
.
.
.
#endif
datatype x;
// Do operation on same variable
}
But now every time the first condition #if INT is getting true.
I tried to set different values of macro to differentiate but not working :(
Can anyone help me achieve the above thing.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//type generic method definition using templates
template <typename T>
void display(T arr[], int size) {
cout << "inside display " << endl;
for (int i= 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int a[10];
string s[10];
double d[10];
for (int i = 0; i < 10; i++) {
a[i] = i;
d[i] = i + 0.1;
stringstream std;
std << "string - "<< i;
s[i] = std.str();
}
display(a, 10); //calling for integer array
display(s, 10); // calling for string array
display(d, 10); // calling for double array
return 0;
}
If you really want your function to be generic, template is the way to go. Above is the way to do and call the method from main method. This might be of some help for you to reuse a function for different types. Pick up any tutorial or C++ books for complete understanding on templates and get a grip of the full concepts. Cheers.
You can use templates to achieve you purpose.
Simply write a template function which take the value in the function argument which is of generic type and put the operational logic inside it. Now call the function with different data types.
I advice you to use function overloading:
void foo(int arg) { /* ... */ }
void foo(long arg) { /* ... */ }
void foo(float arg) { /* ... */ }
Supposing you want do the same operation with integer and long types you can eliminate the code repetition in this way:
void foo(long arg) { /* ... */ }
void foo(int arg) { foo((long) arg); }