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;
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.
Footnote
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.
Related
I am trying to use pointers whenever possible in the following code and am having difficulty figuring out how, exactly, to institute the pointers and how to return a pointer value at the end of my first function. I have done some research on the subject but none of the methods I found have been helpful so far, so I was hoping you may have some specialized tips.
Note: I am a beginner.
#include <iostream>
using namespace std;
int mode(int *pies[], int size) {
int count = 1;
int max = 0;
int *mode=pies[0];
for (int i=0; i<size-1; i++)
{
if (pies[i] == pies[i+1])
{
count++;
if (count>max)
{
max = count;
mode = pies[i];
}
}
else
count = 1;
}
return *mode;
}
int main() {
int n;
cout<<"Input the number of people: "<<endl;
cin>>n;
int survey[n];
cout << "Enter the amount of pie eaten by each person:" << endl;
for(int i = 0; i < n; i++) {
cout <<"Person "<<(i + 1)<< ": "<<endl;
cin>>survey[i];
}
cout<<"Mode: "<<mode(survey, n)<< endl;
return 0;
}
Here is an attempt to answer.
In your main(), you call the mode() function with mode(survey, n) while int survey[n]; is an array of int, so you may use int mode(int *pies, int size) instead of int mode(int *pies[], int size) (as the array int survey[n] can be implicitly converted into pointer).
However, you need to modify two more things in your function:
int *mode=pies[0]; is wrong as pies[0] is the first element of an array of int, thus is an int, while int* mode is a pointer on an int which is incompatible. mode should be an int to receive pies[0]. The correct code is then int mode = pies[0].
Your function signature is int mode(int *pies, int size), thus, again, you should return an int. You should then just return mode;
These are only hints on how to make the code compile.
Your next step is to formalize what you would like it to do and then modify the code accordingly
NB: The correct practice is to think about what you would like to achieve first and then code afterwards (but let us say that this is for the sake of helping each other)
To get started using pointers, you may look at some simple tutorials at first:
http://www.cplusplus.com/doc/tutorial/arrays/
https://www.programiz.com/c-programming/c-pointers
https://www.programiz.com/c-programming/c-pointers-arrays
https://www.geeksforgeeks.org/pointer-array-array-pointer/
https://www.geeksforgeeks.org/how-to-return-a-pointer-from-a-function-in-c/
https://www.tutorialspoint.com/cprogramming/c_return_pointer_from_functions.htm
Here is the modified code with the stated modifications above (it compiles):
#include <iostream>
using namespace std;
int mode(int *pies, int size) {
int count = 1;
int max = 0;
int mode=pies[0];
for (int i=0; i<size-1; i++)
{
if (pies[i] == pies[i+1])
{
count++;
if (count>max)
{
max = count;
mode = pies[i];
}
}
else
count = 1;
}
return mode;
}
int main() {
int n;
cout<<"Input the number of people: "<<endl;
cin>>n;
int survey[n];
cout << "Enter the amount of pie eaten by each person:" << endl;
for(int i = 0; i < n; i++) {
cout <<"Person "<<(i + 1)<< ": "<<endl;
cin>>survey[i];
}
cout<<"Mode: "<<mode(survey, n)<< endl;
return 0;
}
If I run this code:
#include<bits/stdc++.h>
using namespace std;
int hourGlass(int x, int y) {
int sum;
for (int a=y; a<=y+2; a++) {
sum += arr[x][a];
sum += arr[x+2][a];
}
return sum;
}
int main(){
int arr[7][7];
for (int i=0; i<=5; i++) {
for (int j=0; j<=5; j++) {
cin >> arr[i][j];
}
}
for (int i=0; i<=3; i++) {
for (int j=0; j<=3; j++) {
cout << hourGlass(i,j);
}
}
}
It gives the error 'arr' was not declare on this scope. How do I fix this?
Your hourGlass function does not have access to arr which is in the scope of the main function. You can pass arr as a parameter to the function like this:
int hourGlass(int x, int y, int const (&arr)[7][7]) {
// ...
}
and call the function like this:
hourGlass(i, j, arr)
Also, note that sum is uninitialized in your function, so reading from it invokes undefined behavior.
Simply move int arr[7][7] outside of the main() function and put it before int hourGlass(int x, int y). This will make it global, that is, visible to all functions declared after it (not just a single function).
Or, perhaps a better solution (but limited to C++), use some STL container, such as std::vector or std::array, and pass it as a function argument.
#include <iostream>
using namespace std;
struct stud
{
char name[10];
int id;
};
int input(stud a[], int size)
{
for(int i=1; i<=size; i++)
{
cout<<"name = ";
cin>>a[i].name;
cout<<"id = ";
cin>>a[i].id;
}
cout<<endl;
return 0;
}
int output(stud a[], int size)
{
for(int i=1; i<=size; i++)
{
cout<<"name = "<<a[i].name<<" ";
cout<<"id = "<<a[i].id<<" ";
}
cout<<endl;
return 0;
}
int copy(stud a[], stud x[], int size)
{
for(int i=1; i<=size; i++)
{
x[i].name=a[i].name;
x[i].id=a[i].id;
}
output(x,size);
cout<<endl;
return 0;
}
int main()
{
struct stud s[3], x[3];
input(s,3);
output(s,3);
copy(s,x,3);
return 0;
}
In this program the statement in function copy x[i].name =a[i].name; is not copying contents from 1 structure object to another. I have tried to put this statement in for loop for(int j=1;j<=10;j++) x[i].name[j] =a[i].name[j]; but still not working.
please suggest what should be changed or some alternatives for this.
i'll be very thankful to you for this.
regards,
umar
Either using a loop to copy each character in the name field or using thestrcpy function from <cstring> header works.
int copy(stud a[], stud x[], int size) {
for(int i = 1; i <= size; i++) {
// for(unsigned j = 0; j < 10; j++) {
// x[i].name[j] = a[i].name[j];
// }
strcpy(x[i].name, a[i].name);
x[i].id = a[i].id;
}
output(x, size);
cout << endl;
return 0;
}
But since you tagged this as c++, consider using std::string instead of a char array, unless you have a particular reason for using a char array. In that case x[i].name = a[i].name would have worked just fine and you could also use the standard algorithm library for copy. Also, using std::array instead of a raw C array for you "array of structures" might be a better option (does not degenerate into a pointer like a regular C array does).
Evrey single one of your loops is wrong, because in C++ arrays start at zero. So not
for(int i=1; i<=size; i++)
instead
for(int i=0; i<size; i++)
You cannot copy arrays by writing a = b;. Since your arrays are really strings there's a built in function strcpy to copy strings.
strcpy(x[i].name, a[i].name);
If you use = to copy struct, the char array inside that struct will be copied. You don't need to do anything more.
#include <iostream>
using namespace std;
typedef struct{
char name[10];
} type_t;
int main() {
type_t a = {"hihi"};
type_t b;
b = a;
a.name[0] = 'a';
cout<<a.name<<endl;
cout<<b.name<<endl;
return 0;
}
output:
aihi
hihi
ideone: https://ideone.com/Zk5YFd
I wrote down this code in C++ to read a 2D array from a file. Now I'd like to organize better my code with functions. The issue I'm having is that I can't figure out how to pass the 2D array I loaded to memory to another function in the same program.
This is the code I need to organize into functions:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define M 4
#define N 4
int main(){
int i, j;
float A[M][N];
string line;
ifstream matrix("matrix.txt");
if (matrix.is_open())
{
do
{
for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
matrix >> A[i][j];
}
}
while (getline(matrix,line));
matrix.close();
}
else cout << "Unable to open file";
float sumline[M]={0};
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
sumline[i]+=A[i][j];
}
float sumcolumn[N]={0};
for(j=0;j<N;j++)
{
for(i=0;i<M;i++)
sumcolumn[j]+=A[i][j];
}
for (i=0; i<M; i++){
for (j=0; j<N; j++){
if(sumline[i]<sumcolumn[j]){
cout << "Error, total sum of column "<<j<<" is greater than the sum of the line"<<i<<endl;
return 0;
}
}
}
int mincol=sumcolumn[0];
for (i=0; i<N; i++){
if(mincol>sumcolumn[i])
mincol==sumcolumn[i];
}
float avgline = 0.0;
for (i=0; i<M; i++){
avgline=avgline+sumline[i];
}
avgline = avgline/M;
if (avgline * 3 > mincol) {
cout << "Conditions verified"<<endl;
}
else{
cout << "Error, triple of the avg of line is less than the lowest sum of column"<<endl;
return 0;
}
return 0;
}
The code basically does some math on the 2D array. I'd also like to keep as simple as possible so even if using namespace std; it's not really good practice or the way I'm reading the array from the file is really basic I need it to be like that. Thanks a lot.
Instead of using c-array
float A[M][N];
You may instead use
using MyArrayType = std::array<std::array<float>, M>, N>;
MyArrayType A;
Now you can pass by reference (MyArrayType& or const MyArrayType& )
That being said: a c array can be passed as with the more difficult syntax: (float (&a)[M][N]); - it is strongly recommended to use std::array instead where possible.
Like the question says, I am trying to pass multi-dimensional arrays into a function to print it to a file for an engineering project. The format for which the data is inputted CANNOT be changed, so please don't suggest I just input it as a different datatype.
This particular function anticipates a two-dimensional array (although I have others with three dimensions after this one), where nothing is known about the size of the array until run-time. I know I must use pointers to point to each row of the array separately, but I have NO idea what the syntax is for passing it to the function. In the following code, the array in question is 'block'. The main function is just a little testing example I made to try to make it work:
#include<fstream>
using namespace std;
void of_write_blocks(string filename, string block_type[], int **block,
int grid[][3], string grade_type[], int grade[][3], int n_blocks, int m[])
{
ofstream file_out(filename.c_str(),ios::app);
file_out<<"\nblocks\n(\n";
for(int i=0;i<n_blocks;++i) {
file_out<<" "<<block_type[i]<<" ( ";
for(int j=0;j<m[i];++j)
file_out<<block[i][j]<<" ";
file_out<<") ( ";
file_out<<grid[i][0]<<' '<<grid[i][1]<<' '<<grid[i][2]<<" ) ";
file_out<<grade_type[i]<<" ( ";
file_out<<grade[i][0]<<' '<<grade[i][1]<<' '<<grade[i][2]<<" )\n";
}
file_out<<");\n";
}
//testing example:
int main()
{
int block[6][9];
for(int i=0; i<6;++i)
for(int j=0; i<9;++j)
block[i][j] = i*j;
int grid[6][3];
for(int i=0; i<6;++i)
for(int j=0; i<3;++j)
block[i][j] = i*j;
int grade[6][3];
for(int i=0; i<6;++i)
for(int j=0; i<3;++j)
block[i][j] = i*j;
string grade_type[6] = {"simpleGrading"};
string block_type[6] = {"hex"};
int m[6] = {8};
int n_blocks = 6;
of_write_blocks("name",block_type,block,grid,grade_type,grade,n_blocks,m);
}
any help is appreciated!
You can't. Multidimensional arrays are syntactic sugar, and are compiled directly into the code that does manipulations on the array, which is a single memory block. The dimensions are not passed into the function as parameters or anything like that as part of the array, as things are done in e.g. Java or C#.
If you need the dimensions of the array in your function, you'll need to just accept a pointer to the first element of the array, and the dimensions, and do the multiplies and adds to get the right index yourself.
Alternately, use something like a std::vector<std::vector<block>>, which pass the dimensions as part of the object, rather than a built in array.
If you have Boost installed, check out Boost Multi-Array.
For clarity I removed all the irrelevant code from your example.
#include <iostream>
#include <fstream>
using namespace std;
void of_write_blocks(int **block, int bh, int bw){
for(int i = 0; i < bh; ++i)
for(int j = 0; j < bw; ++j)
cout << block[i][j] << " ";
cout << endl;
}
int main(){
int bh, bw;
cin >> bh >> bw;
int** block;
block = new int*[bh];
for(int k = 0; k < bh; k++)
block[k] = new int[bw];
// initialize the array
for(int i = 0; i < bh; i++)
for(int j = 0; j < bw; j++)
block[i][j] = (i*bw) + j;
of_write_blocks( block, bh, bw);
}
In the main we are creating a 2D array and initializing it. Then we pass it to of_write_block, which prints the array. Is that what you wanted to do?
Why can't use a reference of array. See below example:
char c[10];
int i[10][20];
double d[10][20][30];
Write a wrapper function like this:
template<typename T, int SIZE>
void Array (T (&a)[SIZE])
{}
template<typename T, int SIZE1, int SIZE2>
void Array (T (&a)[SIZE1][SIZE2])
{}
template<typename T, int SIZE1, int SIZE2, int SIZE3>
void Array (T (&a)[SIZE1][SIZE2][SIZE3])
{}
This is just an example to demonstrate the syntax which will elegantly receive the array without any copying and also avoids confusing pointers. Also, if you are aware that you are going to use only for int then simply remove the typename and explicitly mention int. i.e.
template<int SIZE>
void Array (int (&a)[SIZE]); // explicitly mention int