Need help passing an array of structure to a function - c++

So, I am currently studying at school and I need to do my homework. I am a beginner in C++ and somehow the compiler shows me an error in my code. Basically, I have a .txt file where the data is stored.
The .txt file looks something like this:
5
Petras 23.25 10.50
Rimas 125.40 1.20
Romas 55.00 1.00
Jurgis 1000.90 0.25
Algis 15.00 25.50
The first line shows how much people in the list we have, so I created integer n.
Next we have a list of people. The list tells the name of the person, how much money he has in different currency, and shows the rate of exchange to euros.
And the problem is that I am trying to find the sum of the money they have in Euros. This is my code.
#define USE_MATH_DEFINES
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
using namespace std;
const int Cn = 100;
const int Cname = 15;
int n;
struct listofpeople {
string name;
double MoneyInOtherCurrency;
double RateOfExchange;
double MoneyInEuros;
};
listofpeople A[Cn + 1];
void data();
void ChangeCurrency();
double sum(double C[], int m);
int main () {
data();
ChangeCurrency();
cout << sum(A[].MoneyInEuros, n);
return 0;
}
//-------------------------------------------------------
void data(){
ifstream is ("U2duom.txt");
is >> n;
char symbols[Cname + 1];
for(int i = 1; i <= n; i++){
is.ignore(80, '\n');
is.get(symbols, Cname);
A[i].name = symbols;
is >> A[i].MoneyInOtherCurrency;
is >> A[i].RateOfExchange;
}
}
//----------------------------------------------------------
void ChangeCurrency(){
for(int i = 1; i <= n; i++){
A[i].MoneyInEuros = A[i].MoneyInOtherCurrency*A[i].RateOfExchange;
cout << A[i].name << " " << A[i].MoneyInEuros << " " <<
A[i].MoneyInOtherCurrency << " " << A[i].RateOfExchange << endl;
}
}
//---------------------------------------------------------------
double sum(double C[], int m){
double a = 0;
for(int i = 1; i <= m; i++){
a= a + C[i];
}
return a;
}
And the problem is that the compiler shows me an error in the line where i try to print the sum. Could anyone help me? Thanks.
EDIT:
My compiler shows this error:
error: expected primary-expression before ']' token
If I specify array elements I want to use, for example:
sum(A[n].MoneyInEuros, n);
The compiler shows this error:
cannot convert 'double' to 'double*' for argument '1' to 'double
sum(double*, int)'

double sum(double C[], int m); takes an array of doubles, but you only have an array of listofpeople. This doesn't work.
You have to change sum so that it takes an array of listofpeople, or you change your data structure from a Structure Of Arrays to an Array of Structures (better for performance, more complex to handle).
Typically, sum requires reimplementing:
double sum(listofpeople *s, int m);
Be aware that in C++, we don't use the [] notation for types.

Related

Compiler error: invalid conversion from 'int' to 'int*' [-fpermissive]

I am having a problem with a program, and I'm getting the error above. However, when I search up the error, everyone else has some sort of int * variable whereas I don't have that all compared to them and is still getting this error.
#include <iostream>
#include <fstream>
const int VALUES = 250;
using namespace std;
void minFinder(int nums[]);
void maxFinder(int nums[]);
void arithmeticMeanFinder(int nums[]);
void geometricMeanFinder(int nums[]);
void standardDeviationFinder(int nums[]);
int main()
{
ifstream file;
int number, counter;
int nums [VALUES];
counter = 0;
file.open("F://Yes/Untitled.txt");
file >> number;
while (!file.fail()){
counter++;
nums [counter-1] = number;
file >> number;}
arithmeticMeanFinder(nums[VALUES]);
file.close();
system("pause");
return 0;
}
void arithmeticMeanFinder (int nums[VALUES])
{
ifstream file;
int ct, holder;
double counter, mean;
double accum = 0;
for (ct = 0; ct < VALUES; ct++){
holder = nums[ct];
accum = accum + holder;
counter++;}
mean = (accum * 1.0) / counter;
cout << counter << " is the arithmetic mean" << endl;
}
This code: arithmeticMeanFinder(nums[VALUES]); index into nums to retrieve the (nonexistent) item at the offset VALUES.
I'd guess you want it to be more like: arithmeticMeanFinder(nums);
The rest of the code isn't exactly what I'd like (e.g., it requires that the number of values in the file be exactly equal to VALUES, or it'll fail miserably), but that's the source of the specific problem the compiler is citing.
In your code, you have:
void arithmeticMeanFinder (int nums[VALUES])
Because of the rules of C++, this is equivalent to:
void arithmeticMeanFinder (int nums[])
And also because of the rules of C++, this is equivalent to:
void arithmeticMeanFinder (int *nums)
So when you call this function, you need to write:
arithmeticMeanFinder(nums); // pass the pointer to first element
Instead of:
arithmeticMeanFinder(nums[VALUES]);
In the call to arithmeticMeanFinder above, by expression nums[VALUES], you pass the VALUES-th element, which is an int, as the argument.
As the array nums has only VALUES items (maximum index is VALUE - 1),
this is an out-of-bound access.

Converting Array of type float to doubles

I really need help on learning how to convert arrays of different types to doubles (short, long, float). I'm not really sure how to ask the question any better. This is for an assignment for school. I understand that the assignment isn't complete, I just need to learn to do this before I continue to make arrays for short and long types.
Assignment Description:
We are going to expand program to account for different primitives. This implementation will implement all 8 functions described in program 2 as templates. To show this works, the main function will declare 4 different arrays that contain 10 values. The different arrays will be declared as shorts, longs, floats, and doubles. Each array will be filled with random values from a random-number generator. The array will be printed, then each of the 8 functions will be called and the results printed to the user. In order to provide a container, each of the functions will be part of a class called “MathHelper” that has all of the functions declared with a public access modifier and a static modifier.
MathHelper.h
#pragma once
class MathHelper
{
public:
static double calculateSum(const double numbers[], const int& count);
static double calculateAverage(const double numbers[], const int& count);
static int highestNum(const double numbers[], const int& count);
//int lowestNum(const int numbers[], const int& count);
//int numRange(const int numbers[], const int& count);
//double standardDeviation(const int numbers[], const int& count);
//int smallestFactorial(const int numbers[], const int& count);
};
MathHelper.cpp
#include "MathHelper.h"
MathHelper::MathHelper()
{
}
double MathHelper::calculateSum(const double numbers[], const int& count)
{
if (count <= 0)
return 0;
double total = 0;
for (int i = 0; i < count; i++)
total += numbers[i];
return total;
}
double MathHelper::calculateAverage(const double numbers[], const int& count)
{
if (count <= 0)
return 0;
return static_cast<double>(calculateSum(numbers, count)) / count;
}
int MathHelper::highestNum(const double numbers[], const int& count)
{
if (count <= 0)
return 0;
int highest = numbers[0];
for (int i = 1; i < count; ++i)
if (highest < numbers[i])
highest = numbers[i];
return highest;
}
MathHelper::~MathHelper()
{
}
Program4.cpp
// Program4Fix.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "MathHelper.h"
#include <iostream>
#include <cmath>
#include <ctime>
#include <iomanip>
int main()
{
const int size = 10;
double* myDoubles = new double[size];
float* myFloats = new double[size];
srand((unsigned)time(NULL));
// double fill
std::cout << std::endl;
std::cout << "Double Array: \n";
for (int i = 0; i < size; i++)
{
*(myDoubles + i) = rand() / double(RAND_MAX)*50.f + 1.f;
std::cout << i << ": " << std::setprecision(4) << *(myDoubles + i) << std::endl;
}
std::cout << std::setprecision(5) << "The sum of the numbers is: " << MathHelper::calculateSum(myDoubles, size) << "\n";
std::cout << std::setprecision(5) << "The average of the numbers is: " << MathHelper::calculateAverage(myDoubles, size) << "\n";
// long fill
std::cout << "Float Array: \n";
for (int i = 0; i < size; i++)
{
*(myFloats + i) = rand() / float(RAND_MAX)*50.f + 1.f;
std::cout << i << ": " << std::setprecision(4) << *(myFloats + i) << std::endl;
}
std::cout << std::setprecision(5) << "The sum of the numbers is: " << MathHelper::calculateSum(myFloats, size) << "\n";
std::cout << std::setprecision(5) << "The average of the numbers is: " << MathHelper::calculateAverage(myFloats, size) << "\n";
return 0;
}
I guess my real question is, is there anyway to use a value of type double* to initialize an entity of type float*?
const int size = 10;
double* myDoubles = new double[size]; // this works
float* myFloats = new double[size]; // this doesn't work, is there a way to do this similar to the one above?
Since you are asking about C++, don't use implicit conversion
double d = 1.5;
int i = d;
Also don't use c-style casting:
double d = 1.5;
int i = (int)d;
Make use of proper casting
int i = static_cast<int>(d);
You can read up on why, there are many reasons why to cast in C++.
For converting the array, you need to create a new array and then iterate over the existing one, convert one by one and then assign them to the new one.
For C++11 you can possibly use the std::transform() function.
I guess what you should do is generalize the functions in MathHelper to template functions which can be used for other types than double. I would get a decent C++ book and read about template functions, e.g. in A Tour of C++ or Programming -- Principles and Practice Using C++. You can get the first four chapters for the Tour of C++ from isocpp.org, and the second chapter introduces templates.
In the end, you should have code that looks like
class MathHelper
{
public:
template<typename T> static double calculateSum(const T numbers[], const int& count);
};
As a general remark, the posted code looks very C-ish meaning that it uses C-constructs where C++ has better alternatives, e.g. manually managed arrays instead of std::vector. You should avoid this.
Converting to double from float, int, or long is as simple as just assigning the source variable to a variable declared double.
For example:
int a = 1
long b = 2;
float c = 3.0f;
double result;
result = a;
result = b;
result = c;
In the 3 last statements, the values will be converted to doubles for you.
You can also convert the other way by casting.
const int size = 10;
double* myDoubles = new double[size];
float* myFloats = new float[size];
InitializeArray(myDoubles); // You'll have to start with some values
for(int i = 0; size > i; ++i)
{
myFloats[i] = (float) myDoubles[i];
}

To write a program to remove duplicates from an array

I am working on program that remove duplicates from an array I am using three functions here: one to take the input such as the size and the number, second function to remove duplicates and return the number without duplicates and the third function just a report show the size and the new number but I am having problem I don't know in what step I think in report or phillip erreur:
In function ‘int main()’: invalid conversion from ‘int*’ to ‘int’,initializing argument 1 of ‘void report(int, int)’
#include <iostream>
using namespace std;
const int size = 100;
void phillip(int[], int & );
/* Preconditions: Array of base type in declared and int varuable declared
postconditions: the array is filled with values supllied by the user at
the keybord. the user is assked how many values they want - this value is
given to the second argument.
*/
int remdubs(int[], int noel);
/* Preconditions: An array of basetype int that has noel values.
postconditions: The number of unique elemts in the array is returned. The function removes all dubplicates inside the array.
*/
void report(int s, int d);
int main()
{
int ruby[size];
int numele, numuniq;
phillip(ruby, numele);
numuniq = remdubs(ruby, numele);
report(ruby, numuniq);
return 0;
}
void phillip(int[], int& )
{
int s;
cout << "\nHow many values you want? ";
cin >> s;
cout << "\nPlease input 10 integers, hitting return after each one \n";
for (int i = 0; i < s; i++)
{
int num;
cin >> num;
}
}
int rembups(int sapphire[], int noel)
{
for (int i = 0; i < noel; i++)
{
for (int j = i + 1; j < noel; j++)
{
if (sapphire[i] == sapphire[j])
{
for (int k = j; k < noel; k++)
sapphire[k] = sapphire[k + 1];
noel--;
j--;
}
}
}
return noel;
}
void report(int s, int d)
{
cout << "\nYou entered " << s << "distinct numbers: " << d;
}
Can't explain it better than your error:
void report (int s, int d);
this function asks for two integer values, you're passing an array to it which, with decayed functionalities, will behave like an integer pointer
int ruby[size];
report (ruby, numuniq);
I'm unsure on the behavior of your program but you should rather do something like
report(ruby[0], numuniq);
that is: access the element of the array and feed it to the function
The error is in the function report, it asks for two integer and you are passing an array and an integer instead
and again i don't think you need 2 parameters in the function report one would solve your purpose
void report(int d)
{
cout << "\nYou entered <<d<<" distinct numbers";
}
that would solve your error but i don't think you would get your desired output
Few problems with the code:
Report function should be expecting an array of integers rather than single integer
Try using human readable variable or function names
remdubs was renamed to rempubs in function definition
phillip function definition didn't have params defined properly
You have const int size but do not use it
remdups has a bug somewhere. I will leave that out as I am trying to fix other issues here.
There are better ways of finding duplicates than remdups. Please look at some other solutions.
I have fixed your code and provided it here on ideone

C++ Array, average value (Beginner)

I need some help creating an array with 10 number that the user can pick. Had a post about this yesterday but misstook arrays for vectors..
Need to calculate the average value of the numbers, need pseudocode for it as well.
Any help would be awesome, I do have a school book but the array examples in it will just not work (as you can se in the code I'll add).
This is what I got sofar:
#include <iostream>
#include <array>
using namespace std;
int main()
{
int n[10];
for (int i = 0; i < 10; i++)
{
cout << "Please enter number " << i + 1 << ": ";
cin >> n[i];
}
float average(int v[], int n)
{
float sum = 0;
for (int i = 0; i < n; i++)
{
sum += v[i]; //sum all the numbers in the vector v
}
return sum / n;
}
system("pause");
}
the part to calculate the average I got help with from the last post I had. But everything else won't work "/ So basicly I need help to make a array with 10 user input numbers. Cheers
The only thing that you wrote correctly is function average. I would add qualifier const to the parameter of the function
#include <iostream>
#include <cstdlib>
using namespace std;
float average( const int v[], int n )
{
float sum = 0.0f;
for ( int i = 0; i < n; i++ )
{
sum += v[i]; //sum all the numbers in the vector v
}
return sum / n;
}
Or statmenet
return sum / n;
could be substituted for
return ( n == 0 ? 0.0f : sum / n );
Take into account that functions shall be defined outside any other functions and a function declaration shall appear before usage of the function.
You need not header <array> because it is not used. But you need to include header <cstdlib> because you use function system.
As it is written in your assigment you need enter arbitrary values for the array
int main()
{
const int N = 10;
int a[N];
cout << "Enter " << N << " integer values: ";
for ( int i = 0; i < N; i++ ) cin >> a[i];
cout << "Average of the numbers is equal to " << average( a, N ) << endl;
system( "pause" );
return 0;
}
int n[10]; - n is an array of ints, not strings, so why are you doing n[0] = "Number 1: ";? You should instead loop and ask for an input from the user.
After you do this, you should place average function outsude the main function and call it from the main.
I advise you to go through a basic tutorial.
Function definition should always be outside main.
int n[10] mean n is array of integers of size 10. They are not array of pointers of type char * to hold strings
There isn't a caller for function average. Subroutines work like, callers will call callee passing arguments to perform operations on them and return them back - pass by reference.

cannot convert ‘double’ to ‘double*’ for argument ‘1’ to ‘float sumall(double arr[])

I am a C & Assembly programmer. But C++ is so dumb. I cannot understand what I am doing wrong here. Can someone explain to me why I am getting this error? Here is my code:
GNU nano 2.2.6 Файл: assignment4.cpp
#include <cstdlib>
#include <iostream>
#define SIZE 10
int counter = 0;
const double TAX = 1.13;
float sumall(double arr[]);
int main (int argc, char **argv)
{ double array[SIZE] = {0,0,0
,0,0,0
,0,0,0
,0};
while (counter < (SIZE-1))
{
if (array[counter-1] == -99)
break;
else continue;
std::cout << "Enter any number [1 WORD long]: ";
std::cin >> array[counter];
++counter;
}
std::cout << "The total price is: $" << sumall(array[SIZE]);
return EXIT_SUCCESS;
}
float sumall(double arr[])
{
float total=0;
for(int i=0;i<SIZE;++i)
{
total+=arr[i];
}
total*=TAX;
return (total*TAX);
}
Also, how can I fix this error using templates (which I heard is possible in C++), thanks!
I think it should be like this :
std::cout << "The total price is: $" << sumall(array);
Also total should be double
double sumall(double arr[])
{
double total=0;
for(int i=0;i<SIZE;++i)
{
total+=arr[i];
}
total*=TAX;
return (total*TAX);
}
you have int counter = 0; and if (array[counter-1] == -99)
in the very first iteration of the loop, you will access index 0 - 1 = -1.
in your sumall function, you declared it to return float, but since you are summing doubles the final value will be double
and you better use const int SIZE = 0, much more safer than using #define
and in your function call to sumall, sumall(array[SIZE]), no need to pass the array size.
just call it like this, sumall(array)