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)
Related
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
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
So, I am working on a code that should solve a maze to be given in a .txt file let's say "input.txt" where 1's = blocks and 0's = open paths in a form like this:
Maze1
7,6 //Number of rows and columns of the maze: row,column
1,1,1,1,1,1
1,0,1,1,0,1
1,0,0,0,0,1
1,0,1,1,0,0
1,0,1,1,0,1
1,1,0,0,1,1
1,1,1,1,1,1
1 // number of entrances
1,2 // coordinate of an entrance relative to the origin: row, column
So I have got some algorithm in my mind, but let's say the "1st" entrance is invalid...
so the output should be like this :
Maze1
Entrance: 1,2 Invalid
And this should be printed in another .txt file let's say "Output.txt".... but it actually gives me no syntax errors, yet it doesn't write anything to the Output.txt...
Anyways here's my "Incomplete-Code" ... so please help me :
#include <stdio.h>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Stack
{
int data[30]; //X should be constant
int top;
}; //Stack
void Push(int a,Stack &S)
{
S.top++;
if (S.top>=30) //Remember X should be constant
{
cout<<"The stack is full!"<<endl;
S.top--;
return;
}
else
{
S.data[S.top]=a;
}
} //Push
int Pop(Stack &S)
{
if (S.top==-1)
{
cout<<"The stack is empty!"<<endl;
return 0;
}
else
{
int Temp=S.data[S.top];
S.data[S.top]=NULL;
S.top--;
return Temp;
}
} //Pop
int main ()
{
#define false 1;
#define true 0;
string line;
Stack s1 = { NULL, -1 }, s2 = { NULL, -1 };
int x, y; //Dimensions of Matrix.
int z; //Element Location in Matrix.
int a; //Number of Entrance Points.
int b, c; //Coordinates of Entrance Points.
char ch; //Comma indication.
ifstream input ("Input.txt"); //Using relative addresses.
ofstream output ("Output.txt");
input>>line;
cout<<"Solution for "<<line<<" : \n \n \n";
input>>x>>ch>>y; //Reading the Dimensions of the Matrix.
cout<<line<<" coordinates are "<<x<<ch<<y<<endl<<endl<<endl;
int **Maze = new int *[x]; //Creating Dynamic Matrix.
for (int i=0; i<x; i++)
{
Maze[i]= new int [y];
}
for (int i=0; i<x; i++) //Filling the Maze from the .txt
{
for (int j=0; j<y; j++)
{
input>>z;
Maze[i][j]=z;
}
}
input>>a; //Reading the number of entrances.
for(int i=0; i<a; i++)
{
input>>b>>ch>>c; //Reading the entrance coordinates.
if (Maze[b][c]==1 || b>7 || c>6) //Checking for the validity of entrance point.
{
cout<<"Entrance: "<<b<<ch<<c<<" is Invalid! \n";
output<<"Entrance: "<<b<<ch<<c<<" is Invalid! \n";// WRITE ENTRANCE IS INVALID IN OUTPUT FILE
}
}
output.close();
input.close();
for(int i=0; i<x; i++) //Deleting Maze
{
delete[] Maze[i];
}
delete[] Maze;
return 0;
}
So where's the mistake ?
Arrays in C++ are 0-indexed - that is, Maze[1][2] is the cell in the second row, third column. Either number your entrance cell like that in the input file, or subtract 1 from each co-ord in the code.
Also, when parsing the maze itself, you don't seem to be taking account of the commas.
I have a data file which contains 49 numbers + 1 word and another file that contains 50 numbers. My task is to compute the mean, standard deviation and standard error for both. At the moment I have a code which will happily compute the correct values for the file containing only numbers. How do I remove the character?
I a beginner and unsure how to correctly use the getline() function to put data from the file into a string and then somehow use cin.ignore() and cin.clear() to remove the character? Help would be appreciated!
Program:
// Assignment 2: Milikan data programme
#include "stdafx.h"
#include<iostream>
#include<iomanip>
#include<fstream>
#include<cmath>
#include<string>
using namespace std;
//Mean function
double mean(double *mydata, double N)
{
double sum(0), m;
for (int i=0; i<N; i++)
{
sum += mydata[i];
}
m = (sum/(double)N);
return(m);
}
//Standard deviation function
double standard_dev(double *mydata, double m, int N)
{
double *mydata2 = new double[N];
for (int i=0; i<N; i++)
{
mydata2[i] = pow((mydata[i]-m), 2);
}
double sum(0), S, X;
for (int i=0; i<N; i++)
{
sum += mydata2[i];
}
X = sum/(N-1);
S = sqrt(X);
return (S);
}
int main ()
{
int N(0);
char filename[100];
double m, sterr, stdev;
string temp;
cout<<"Please enter the number of data points: ";
cin>> N;
cout<<"Please enter the name of the file: ";
cin>>filename;
//Dynamic memory allocation for N data points in array mydata
double *mydata;
mydata = new double[N];
//Open file and attach chosen file to myfile
ifstream myfile;
myfile.open(filename);
//Check it opened sucessfully
if(!myfile.is_open())
{
cerr<<"\nError: file could not be opened!"<<endl;
system("PAUSE");
return(1);
}
//Detect and ignore rogue character???
//Read data from the file into an array
for (int i=0; i<N; i++)
{
myfile>>mydata[i];
}
m = mean(mydata, N);
stdev = standard_dev(mydata, m, N);
sterr = 1/stdev;
cout<<"\nThe mean charge of an electron is : "<<m<<" eV"<<endl; /
cout<<"The standard deviation of results is : "<<stdev<<endl;
cout<<"The standard error of results is : "<<sterr<<endl;
myfile.close(); //Close file
delete[] mydata; // Free memory
system("PAUSE");
return 0;
}
Also remember that the stream objects failbit becomes set if the extraction of a number fails. You can check for that, and if set you skip all non-digit characters in the stream until you see a digit again.
Something like this pseudo code:
while (myfile)
{
myfile >> value;
if (myfile.fail())
{
clear_failbit();
while (next_character_is_not_digit())
get_and_discard_next_character();
}
}
Of course, a better solution would probably be to not generate files containing errors.
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++)