Using FOR loops to put data into ref arrays - c++

I've tried to debug my program yet it isn't helping. I've only used WHILE loops to put data into arrays but I figured using a FOR loop here would be easier.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct record
{
int item_id;
string item_type;
int item_price;
int num_stock;
string item_title;
string item_author;
int year_published;
};
void read_all_records(record records[]);
int num_inventory_of_type(record records[]);
const int max_array = 100;
int main()
{
record records[max_array];
read_all_records(records);
cout << records[1].item_author;
num_inventory_of_type(records);
return 0;
}
void read_all_records(record records[])
{
ifstream invfile;
invfile.open("C:\\Users\\acsindle\\Dropbox\\Prog2\\Asg22\\Asg22\\inventory.dat");
if (!invfile.is_open())
{
cout<<"file open failed";
exit(1);
}
int slot = 0;
for (int count = 0; count<max_array; count++)
{
invfile >> records[slot].item_id >>
records[slot].item_type >>
records[slot].item_price >>
records[slot].num_stock >>
records[slot].item_title >>
records[slot].item_author >>
records[slot].year_published;
slot++;
}
invfile.close();
}
int num_inventory_of_type(record records[])
{
int slot = 0;
int book = 0;
int dvd = 0;
int cd = 0;
for (int count = 0; count>max_array; count++);
{
if (records[slot].item_type == "book")
book++;
if (records[slot].item_type == "dvd")
dvd++;
if (records[slot].item_type == "cd")
cd++;
}
return book, dvd, cd;
}
My .dat file is as follows:
123456 book 69.99 16 Problem_Solving_With_C++ Walter_Savitch 2011
123457 cd 9.99 32 Sigh_No_More Mumford_and_Sons 2010
123458 dvd 17.99 15 Red_State Kevin_Smith 2011
123459 cd 9.99 16 The_Church_Of_Rock_And_Roll Foxy_Shazam 2012
123460 dvd 59.99 10 The_Walking_Dead_Season_1 Robert_Kirkman 2011
They're all separate on a single line with no spaces so there is no need to splice them. It should just be as easy as cin and stored. Not sure if it's my FOR loop that is messed up or if it's an issue with passing the array. Also my array is tied into my struct, is there a term for this? Is this what is considered a multidimensional array?

The terminating condition is incorrect and there is a trailing semi-colon:
for (int count = 0; count>max_array; count++);
Change to:
for (int count = 0; count<max_array; count++)
Also slot is not incremented in the for, and only cd will be returned by the num_inventory_of_type() function: you can't return three values like that from a function.
A possible implementation:
void num_inventory_of_type(record records[], int& book, int& dvd, int& cd)
{
for (int slot = 0; slot<max_array; slot++)
{
if (records[slot].item_type == "book")
book++;
if (records[slot].item_type == "dvd")
dvd++;
if (records[slot].item_type == "cd")
cd++;
}
}
You should check the state of invfile during read to ensure no failures.

Should have count<max_array; rather than count>max_array;

Your for condition doesn't seem right, plus you got a semicolon that shouldn't be there at the end of the for
for (int count = 0; count>max_array; count++);
The test will return false at the first iteration
for (int count = 0; count<max_array; count++)

Related

How do I use pointers with arrays in c++ and return a pointer value?

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;
}

Reading integers from an input file, storing only the unique integers in the array C++

I've been stuck on this homework question for a couple of days now. I did some research and I got to this:
#include<iostream>
#include<fstream>
#include<string>
#include<array>
using namespace std;
const int MAX_SIZE = 100;
bool RepeatCheck(int storage[], int size, int checker);
int main()
{
ifstream input("input.txt");
if (!input) // if input file can't be opened
{
cout << "Can't open the input file successfuly." << endl;
return 1;
}
int storage[MAX_SIZE];
int inputCount;
int checker;
while (!input.eof())
{
for (int i = 0; i <= MAX_SIZE; i++)
{
input >> checker;
if (!RepeatCheck(storage, MAX_SIZE, checker))
{
input >> storage[i];
}
}
}
// print array
for (int i = 0; i < 100; i++)
{
cout << storage[i] << " ";
}
return 0;
}
bool RepeatCheck(int storage[], int size, int checker)
{
for (int i = 0; i <= MAX_SIZE; i++)
{
if (storage[i] == checker)
{
return false;
}
}
}
My input file needs to be filled with integers separated by white space or on new lines:
1 2 2 3 5 6 5
4 3 20 34 5 7
5 2 4
6 3 3 4 5
7 6 7 8
I need to read the integers from the file and store them in the storage[] array only if they aren't already in the array.
It's not doing what I need it to do. Please take a look at my code and tell me where the logic error is. Much appreciated.
If std::set is allowed, use it instead of doing your own duplication check.
For your code, the problem happens here:
while (!input.eof())
{
//for loop not needed
for (int i = 0; i <= MAX_SIZE; i++) //increment regardless whether input is successful or not?
{
input >> checker; //take in a number
//if the number is not repeated
if (!RepeatCheck(storage, MAX_SIZE, checker))
{
input >> storage[i]; //read in another number to put it?
}
}
}
Also here
bool RepeatCheck(int storage[], int size, int checker)
{
for (int i = 0; i <= MAX_SIZE; i++)
//check all values in the array regardless whether it has been used or not?
//should just check until the end of used space, which is what size is meant for
{
if (storage[i] == checker)
{
return false;
}
}
//there should be a return true here right?
}
Have a look at this link to see why while (!iostream.eof()) is considered wrong.
The first part should look like this:
int i = 0;
while (input >> checker)
{
if (!RepeatCheck(storage, i, checker))
{
storage[i] = checker;
++i;
}
}
For second part, use size instead of max size

How to make a while loop till there is something to be readen c++

I know that you probably gona again vote me down, I really don't understand this but im really stuck at something and cant figure it out , there is no such information anywhere in the web , neither in my book for the course, so I have this assignment where I need make 2 sums of containers where the difference between 2 sums is the lowest , so the program is done is working perfectly calculated everything however , in my assignment:
The user enter on one row unkwonw length numbers so after that I do all kind of sums between them and find the one with lowest difference between.
Ok but the way I wrote the code I use one while(true) so that to work with infinity testcases(as from assignment) and in this while(true) I have another while(cin>>(SOMEINT)) loop and push it back in a vector , and after it reads new line it just break the wile and continue with the calculation.
However in our test software this one give runtime error since after finding some cases then it start print infinity 0 0 since there is nothing to enter but the while(true) just continues.
I mean I just want to make it that way that the while is till user enters something , for instance you enter 30 50 90 it will return 80 90 , then wiat for another entry and so on.
CODE:
#include <iostream>
#include <string>
#include<vector>
#include <sstream>
#include <cmath>
#include <string.h>
#include <stdio.h>
#include <climits>
using namespace std;
const int length = 17000;
int power(int x){
int sum =2;
for(int i = 0;i<x;i++) {
sum *= 2;
}
return sum;
}
bool ison(int i,int x)
{
if((i>>x) & 1)return true;
return false;
}
int main()
{
while(true){
vector<int> Vec;
int cur = 0;
while (cin >> cur) {
Vec.push_back(cur);
if (cin.get() == '\n') {
break;
}
}
int * sumOfarr1 = new int[length];
int * sumOfarr2 = new int[length];
for(int i = 0; i<length;i++){
sumOfarr1[i] = 0;
}
for(int i = 0; i<length;i++){
sumOfarr2[i] = 0;
}
int index=0;
for(int i=1;i<length;i++)
{
for(int j=0;j<Vec.size();j++)
{
if(ison(i,j))
{
sumOfarr1[index]+=Vec[j];
}
else
{
sumOfarr2[index]+=Vec[j];
}
}index++;
}
int ans=INT_MAX;
int ii;
for(int i=0;i<index;i++)
{
if(abs(sumOfarr1[i]-sumOfarr2[i])<ans)
{
ii=i;
ans=abs(sumOfarr1[i]-sumOfarr2[i]);
}
}
if(sumOfarr1[ii]<sumOfarr2[ii]){
cout << sumOfarr1[ii] << " " << sumOfarr2[ii];
}
else{
cout << sumOfarr2[ii] << " " << sumOfarr1[ii];
}
cout << endl;
delete[] sumOfarr1;
delete[] sumOfarr2;
Vec.clear();
}
return 0;
}
Yes I found the solution just using getline and stringstream.
aka this
vector<int> Vec;
string line;
while(getline( cin, line ))
{
istringstream iss( line );
int number;
while( iss >> number )
Vec.push_back(number);
}

Matrix subtraction program c++

I'm very new to programming, and I have a project where I need to take in two 6-by-2 matrices from a separate data file containing the life expectancy of black and white males/females in each decade from 1950 to 2000, then subtract the matrices to form a third 6-by-2 matrix containing the difference between the life expectancy of males and females of the same race in each decade. We didn't cover multidimensional arrays in class, and I'm a bit confused by this. I get a lot of errors saying undeclared identifier. I also know there has to be a better way to get the arrays from the data file, but I'm not sure how. Sorry if this is a stupid question.
#include <iostream>
#include <fstream>
using namespace std;
void getMatrixFemaleW();
void getMatrixFemaleB();
void getMatrixMaleW();
void getMatrixMaleB();
void matrix_diff();
int main()
{
float matrixFemale[6][2];
getMatrixFemaleW;
getMatrixFemaleB;
float matrixMale [6][2];
getMatrixMaleW;
getMatrixMaleB;
float matrixDifference[6][2];
matrix_diff;
for (int x=0; x<6; x++)
{
for (int y=0; y<2; y++)
{
cout << matrixFemale[x][y] << " ";
}
cout << endl;
}
}
void getMatrixFemaleW()
{
ifstream inputFile;
inputFile.open("MatrixFemaleW.txt");
int count = 0;
while (count < 6 && inputFile >> matrixFemale[count][0])
count++;
}
void getMatrixFemaleB()
{
ifstream inputFile;
inputFile.open("MatrixFemaleB.txt");
int count = 0;
while (count < 6 && inputFile >> matrixFemale[count][1])
count++;
}
void getMatrixMaleW()
{
ifstream inputFile;
inputFile.open("MatrixMaleW.txt");
int count = 0;
while (count < 6 && inputFile >> matrixMale[count][0])
count++;
void getMatrixMaleB()
{
ifstream inputFile;
inputFile.open("MatrixMaleB.txt");
int count = 0;
while (count < 6 && inputFile >> matrixMale[count][1])
count++;
}
void matrix_diff()
{
for (i=0; i<6; i++)
{
matrixDifference[i][0] = matrixFemale [i][0] - matrixMale[i][0];
}
for (i=0 i<6; i++)
{
matrixDifference [i][1] = matrixFemale [i][1] - matrixMale [i][1];
}
}
first these lines should be
getMatrixFemaleW();
getMatrixFemaleB();
getMatrixMaleW();
getMatrixMaleB();
matrix_diff();
because they are fuctions not variables you need to call them not declear them
then if you wanna reach a variable from outher function it should be global variable or a pointer that means
float matrixFemale[6][2];
float matrixMale [6][2];
float matrixDifference[6][2];
make these variables global variable or pointers

Reading from a data file to 2D array. No output. C++

I am new to programming and c++. I am working on an assignment which requires me to read data from a data file and store it into a 2D array. Every line in the text file is in the following format(data type is int)
XXXX XX XX XX XX ...(and so on)
The four digit number is actually student ID and is to be stored in a separate 1D array. I have done this part and I don't have any issues. Now the rest 2 digit numbers are to be stored in a 2D array with 4 columns and X rows, where X is the number of lines in the data file.
I have written the following code to try to read into the file. It gives no error and compiles correctly but when I try to print the 2D array, using cout, I don't get anything. Nothing. Please look at the following code and try to help me.
I am new to stackoverflow and programming so please forgive me if the code is not formatted correctly or is not as per the tradition.
//___CODE____
#include<iostream>
#include<iomanip>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
//Global
const int SIZE = 1000;
int const col = 4;
string fileName;
//Function Prototypes
int readId(int id[], int size);
int readScores(int scores[][col], int size);
//Main
int main()
{
int examScores[SIZE][col];
int id[SIZE] = {};
cout<<endl;
readId(id, SIZE);
readScores(examScores, SIZE);
}
//Declarations
int readId(int id[], int size)
{
ifstream inputFile;
int count = 0;
int total = 0; //Size of id [] OR no. of students.
int temp = 0;
//Takes the name of the data file from the user.
//NOTE: The filename should include its extension.
cout<<"Enter the name of the data file (including the extension):";
cin>>fileName;
inputFile.open(fileName.c_str());
if(inputFile.is_open())
{
while(inputFile >> temp)
{
if(count % 5 == 0)
{
id[total] = temp;
total++;
}
++count;
}
}
else
cout<<"Data file not found!"<<endl; // If this is executed make sure the data file
//is located in the same directory as this program.
//To print the content of array. Check.
for(int i=0; i < total; i++)
cout<<id[i]<<endl;
return total;
}
int readScores(int scores[][col], int size)
{
ifstream inputFile;
int count = 0;
int c = 0; //Counter for column.
int total = 0; //No. of students.
int temp = 0;
inputFile.open(fileName.c_str());
if(inputFile.is_open())
{
while(inputFile >> temp)
{
if(count % 5 != 0)
{
if (c < col)
{
scores[total][c] = temp;
}
else
total++;
c = 0;
scores[total][c] = temp;
}
++count;
c++;
}
}
else
cout<<"Data file not found!"<<endl; // If this is executed make sure the data file
//is located in the same directory as this program.
//To print the contents of 2D array. Check.
for (int r = 0; r < total; r++)
{
for (c = 0; c < col; c++)
{
cout<<setw(8)<<scores[r][col];
}
cout<<endl;
}
return total;
}
Your else-Statement is wrong, there are some brackets missing (now you always reset c to zero)