Reputation: 215
I code a program to calculate all possibilities, but with integers and now I have to do it for floats, how can I change the program to input floats instead of integers? This is just a part but if I can do it for the fist switch I can do it for all:
#include <fstream>
using namespace std;
ifstream in("multimi.in");
ofstream out("produs.out");
void input(int *v)
{
for(int i=1; i<=2; i++)
in>>v[i];
}
int main()
{
float a[3],b[3],c[3],d[3],e[3],s[3];
int num_tot;
in>>num_tot;
switch(num_tot)
{
case 2:
input(a);
input(b);
for(int i=1; i<=2; i++)
for(int j=1; j<=2; j++)
out<<a[i]<<","<<b[j]<<endl;
break;
This is the code with int which works:
#include <fstream>
using namespace std;
ifstream in("multimi.in");
ofstream out("produs.out");
void input(int *v)
{
for(int i=1; i<=2; i++)
in>>v[i];
}
int main()
{
int a[3],b[3],c[3],d[3],e[3],s[3];
int num_tot;
in>>num_tot;
switch(num_tot)
{
case 2:
input(a);
input(b);
for(int i=1; i<=2; i++)
for(int j=1; j<=2; j++)
out<<a[i]<<","<<b[j]<<endl;
break;
Upvotes: 3
Views: 377
Reputation: 23832
If you want to parse a float
value in your input
function you'll have to have a compatible parameter, as you are passing an array of floats as an argument (which becomes a pointer to the first element of the array), you'll need a pointer to float
instead of pointer to int
.
void input(float *v){ ... }
I should also note that you are bypassing the first element in the array, the indexes start at [0]
.
Another thing I would do is to avoid using global variables, if you want to use your in
stream in the function you can pass it by reference as an argument of the function, provided that you know its lifetime will outlive the reference:
All things considered you would have something like this:
void input(float *v, ifstream& in)
{
for (int i = 0; i < 2; i++)
in >> v[i];
}
int main()
{
ifstream in("test.txt");
ofstream out("produs.out");
float a[2], b[2];
int num_tot;
if (in.is_open() && out.is_open()) //it's important to check for successful file opening
{
in >> num_tot;
switch (num_tot)
{
case 2:
input(a, in);
input(b, in);
for (int i = 0; i < 2; i++)
{
out << a[i] << ", " << b[i] << endl;
}
break;
}
}
}
If you want something that works for both int
and float
you can make a function that can take both types using templates, I'll admit that this may be too much for now but it's somenthing that you may consider when you are more comfortable with the language:
template<typename T> void input(T& v, ifstream& in)
{
for (int i = 0; i < 2; i++)
in >> v[i];
}
Here T
can take both int
or float
, with the added advantage that it can also be passed by reference. Of course you can still use pointers if you wish to do so, but passing by reference is preferable as it's safer.
Consider not using using namespace std;
you can follow this link to know the reasons for it, when it's safe to use and alternatives.
Upvotes: 1