How do I combine matrices with files in C++? - c++

I am trying to create a program to combine two matrices. The first is to add them, the second is to subtract them, but I am getting an 1120 error. I don't know if that's because my code is bad, or if there's something wrong with my compiler. Here's what I've tried.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream matrix_file("matricies.txt");
fstream result1_file("result1.txt");
fstream result2_file("result2.txt");
matrix_file.open("matricies.txt", ios::in);
if (!matrix_file) {
cout << "File was not opened!" << endl;
}
else {
cout << "File opened successfully!";
}
result1_file.open("result1.txt", ios::app);
if (!result_file) {
cout << "File was not created!" << endl;
}
else {
cout << "File created successfully!";
}
result2_file.open("result1.txt", ios::app);
if (!result_file) {
cout << "File was not created!" << endl;
}
else {
cout << "File created successfully!";
}
int matrix1[9];
int matrix2[9];
int result1Matrix[9];
int result2Matrix[9];
for (int i = 0; i < 9; ++i)
{
matrix_file >> matrix1[i];
}
for (int i = 0; i < 9; ++i) {
matrix_file >> matrix2[i];
}
for (int i = 0; i < 9; ++i) {
result1Matrix[i] = matrix1[i] + matrix2[i]
}
for (int i = 0; i < 9; ++i) {
result2Matrix[i] = matrix1[i] - matrix2[i]
}
for (int i = 0; i < 9; ++i) {
result1_file >> result1Matrix[i] ;
}
for (int i = 0; i < 9; ++i) {
result2_file >> result2Matrix[i];
}
matrix_file.close();
result1_file.close();
result2_file.close();
}

Line 35, 38: expected ';' in end line
Output file (result_file) must use operator '<<' instead of '>>'.

Related

How to output functions output into file?

I have a project that requires me to output the data from 2 files. Put them into their own arrays. Calculate the data from 1 of the files into a function. Then output the functions into a whole new file. This is what I have so far and right now I'm trying to figure out how to output the function output into a new file. When I try now, I get outputs in the file like "NULL NULL". I also have to align the data in columns.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
char states();
char stData();
char states()
{
const int SIZE = 0;
ifstream myfile("csc114_states.txt");
string line, myArray[SIZE];
if (myfile.is_open())
{
for (int i = 1; i < SIZE; i++)
{
myfile >> myArray[i];
cout << myArray[i];
cout << endl;
}
myfile.close();
}
myfile.open("csc114_states.txt");
if (myfile.is_open())
{
string tp;
while (getline(myfile, tp))
{
cout << tp << "\n";
}
myfile.close();
}
else
{
cout << "Unable to open file." << endl;
return 0;
}
return 0;
}
char stDATA()
{
const int size1 = 0;
const int size2 = 0;
string myArray2[size1][size2], line;
ifstream myfile2("csc114_data.txt");
if (myfile2.is_open())
{
for (int i = 0; i < size1; i++)
{
for (int j = 0; j < size2; j++)
{
myfile2 >> myArray2[i][j];
cout << myArray2[i][j];
cout << endl;
}
}
myfile2.close();
}
myfile2.open("csc114_data.txt");
if (myfile2.is_open())
{
string tp2;
while (getline(myfile2, tp2))
{
cout << setw(0) << tp2 << "\n";
}
myfile2.close();
}
else
{
cout << "Unable to open file." << endl;
return 0;
}
return 0;
}
int main()
{
ofstream bigFile("csc114_output.txt");
if (bigFile.is_open())
{
bigFile << states() << stDATA();
bigFile.close();
}
else
{
cout << "Unable to open files.";
}
return 0;
}

C++ code crashes instantly due to memory issues

This code should read a .pnm file. I tried to run it with 2 resolutions:
200x200 px: Here everything works just fine.
500x281 px: Code instantly crashes, raising a SIGSEGV error.
As far as I know, SIGSEGV is related to memory issues. I have 8GB of RAM, a quantity that I judge to be enough to run this. I don't have any idea about why it's happening and how to fix it.
Code
#define IO_ERROR (5)
#define X_DIMENSION (500)
#define Y_DIMENSION (281)
#define C_DIMENSION (3)
#define HEADER_SIZE (3)
#define BODY_SIZE (X_DIMENSION * Y_DIMENSION * C_DIMENSION)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int readImage(string fileName, string *imgHeader, string *imgBody)
{
ifstream inputFile(fileName);
if (!inputFile.is_open())
return IO_ERROR;
string line;
int count = 0;
while (getline(inputFile, line)) {
if (line.find("#") != string::npos)
continue;
if (count < 3)
imgHeader[count] = line;
else
imgBody[count - HEADER_SIZE] = line;
count++;
}
inputFile.close();
return 0;
}
void numericParser(const string *imgBody, unsigned char *numericBody)
{
int i = 0;
while(i < BODY_SIZE) {
numericBody[i] = (unsigned) atoi(imgBody[i].c_str());
i++;
}
}
void rgbParser(const string *imgBody, unsigned char rgbMatrix[X_DIMENSION][Y_DIMENSION][C_DIMENSION])
{
unsigned char numericBody[BODY_SIZE];
numericParser(imgBody, numericBody);
int k = 0;
for (int i = 0; i < X_DIMENSION; i++) {
for (int j = 0; j < Y_DIMENSION; j++) {
for (int c = 0; c < 3; c++) {
rgbMatrix[i][j][c] = numericBody[k];
k++;
}
}
}
}
void printInfo(const string *header, const string *body)
{
cout << "#-*- Image Header -*-" << endl;
for (int i = 0; i < HEADER_SIZE; i++) {
cout << header[i] << endl;
}
cout << "#-*- Image Body -*-";
for (int i = 0; i < 5 * C_DIMENSION; i++) {
if (i % 3 == 0) cout << endl << "R: " << body[i];
else if (i % 3 == 1) cout << " G: " << body[i];
else cout << " B: " << body[i];
}
cout << endl << ". . ." << endl;
}
int main()
{
string fileName;
cout << "File name: ";
cin >> fileName;
string imgHeader[HEADER_SIZE];
string imgBody[BODY_SIZE];
if(readImage(fileName, imgHeader, imgBody) == IO_ERROR)
return IO_ERROR;
// printInfo(imageData);
unsigned char rgbMatrix[X_DIMENSION][Y_DIMENSION][C_DIMENSION];
rgbParser(imgBody, rgbMatrix);
return 0;
}
Additional Info
I'm on Arch Linux 64-bit, using CLion as IDE.

bubble sort crashing program c++

So I've been working on a project for class and everything was going swimmingly, until I had to sort the information by last name in ascending order. To elaborate further, in my program I am supposed to take file input, apply it into whatever kind of variables I see fit, calculate their grades by comparing their answers against an answer key, and then sort the entries by last name. Without further ado here is my code! (be gentle)
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <algorithm>
const int TEST_SIZE = 10;
using namespace std;
struct StudentInfo
{
int id;
string fName;
string lName;
char testAnswers[10];
int totalPoints = 0;
int avg = 0;
char letterGrade;
};
void inputInfo(char[], StudentInfo[]);
void calcGrade(char[], StudentInfo[]);
void bubbleSort(StudentInfo[]);
void outputInfo(StudentInfo[]);
int main()
{
StudentInfo studentInfo[10];
string temp;
char answerKey[10];
inputInfo(answerKey, studentInfo);
calcGrade(answerKey, studentInfo);
bubbleSort(studentInfo);
outputInfo(studentInfo);
return 0;
}
void inputInfo(char answerKey[], StudentInfo studentInfo[])
{
cout << "Please enter the 10-question answer key: \n";
for(int i = 0; i < TEST_SIZE; i++)
{
cout << "Question " << i+1 << "\n";
cin >> answerKey[i];
}
ifstream inFile("student.txt");
for(int i = 0; i < TEST_SIZE; i++)
{
inFile >> studentInfo[i].id;
inFile >> studentInfo[i].fName;
inFile >> studentInfo[i].lName;
for(int j = 0; j < TEST_SIZE; j++){
inFile >> studentInfo[i].testAnswers[j];
}
}
}
void calcGrade(char answerKey[], StudentInfo studentInfo[])
{
for(int i = 0; i < TEST_SIZE; i++)
{
for(int j = 0; j < TEST_SIZE; j++)
{
if(studentInfo[i].testAnswers[j] == answerKey[j])
{
studentInfo[i].totalPoints += 5;
}
studentInfo[i].avg = studentInfo[i].totalPoints * 2;
if(studentInfo[i].avg >= 90)
{
studentInfo[i].letterGrade = 'A';
}
else if(studentInfo[i].avg >= 80)
{
studentInfo[i].letterGrade = 'B';
}
else if(studentInfo[i].avg >= 70)
{
studentInfo[i].letterGrade = 'C';
}
else if(studentInfo[i].avg >= 60)
{
studentInfo[i].letterGrade = 'D';
}
else
{
studentInfo[i].letterGrade = 'F';
}
}
}
}
void bubbleSort(StudentInfo studentInfo[])
{
StudentInfo temp;
int i;
int j;
for(i = 0; i < (TEST_SIZE-1); i++)
{
for(j = 0; j < TEST_SIZE; j++)
{
if(studentInfo[j].lName < studentInfo[j-1].lName)
{
temp = studentInfo[j];
studentInfo[j] = studentInfo[j-1];
studentInfo[j-1] = temp;
}
}
}
}
void outputInfo(StudentInfo studentInfo[])
{
cout << setprecision(1) << fixed;
cout << "Student ID\tStudent Name\tAnswers\tTotal Pts\tAverage\t Letter Grade" << endl;
for(int i = 0; i < TEST_SIZE; i++)
{
cout << studentInfo[i].id << "\t";
cout << studentInfo[i].lName << " ";
cout << studentInfo[i].fName << "\t";
for(int j = 0; j < TEST_SIZE; j++)
{
cout << studentInfo[i].testAnswers[j];
}
cout << "\t" << studentInfo[i].totalPoints << "\t";
cout << studentInfo[i].avg << "\t";
cout << studentInfo[i].letterGrade << "\n";
}
}
I've tried everything within my meager abilities, but my program always crashes. Assumedly during the bubble sort since it works fine without that section. If someone could enlighten me as to where I erred I would be very grateful. Sorry for any inconvenience that I've caused.
What happens here
temp = studentInfo[j];
studentInfo[j] = studentInfo[j-1];
studentInfo[j-1] = temp;
when j==0? You access out of bounds. You're better off using std::swap from <algorithm> like
std::swap(studentInfo[j], studentInfo[j+1]);
making sure that you run j until TEST_SIZE - 1. Or write the "manual" swap but with j exchanged by j+1.

C++:Storing a text file

i wrote a simple program(C++) that take 20 numbers and sort them into ascending order.Now i want to save the actions in the program in a file like "num.txt" with . Can you explain me what changes should i do?
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
int main() {
int x[21], s;
int j,i;
for (int i = 1; i < 21; i++)
{
cout << setw(11) << i << ": ";
cin >> x[i];
}
for (int i = 1; i < 21; i++)
{
for (int j = i+1; j < 21; j++)
{
if (x[j] < x[i])
{
s = x[j];
x[j] = x[i];
x[i] = s;
}
}
}
cout << endl;
for (int i = 1; i < 21; i++)
{
cout << i << ": ";
cout << x[i] << "\t";
if (i % 5 == 0)
{
cout << endl;
}
}
getch();
return 0;
}
i know it's simple but i just started since few days ago and i'm novice.
To output the numbers to a file you can use std::ofstream for the output stream and replace cout with the variable name you use for the stream.
std::ofstream outfile;
outfile.open("num.txt");
for (int i = 1; i < 21; i++)
{
outfile << i << ": ";
outfile << x[i] << "\t";
if (i % 5 == 0)
{
outfile << std::endl;
}
}
outfile.close();
You can also take it a step further and add input validation and use components from the Standard Library to handle most of what you are trying to accomplish. For instance instead of storing the numbers in an array I suggest using std::vector instead. You can also use std::sort to sort the data instead of implementing it yourself.
#include <vector> // vector
#include <fstream> // fstream
#include <algorithm> // sort
#include <iostream>
int main()
{
std::vector<int> numbers;
while(numbers.size() != 20)
{
int value;
if(!(std::cin >> value))
{
std::cout << "you must enter a number" << std::endl;
}
else
{
numbers.push_back(value);
}
}
// Do the sort. Pretty easy huh!
std::sort(numbers.begin(), numbers.end());
std::ofstream outfile;
outfile.open("num.txt");
if(outfile.is_open() == false)
{
std::cout << "Unable to open num.txt" << std::endl;
}
else
{
for(size_t i = 0; i < numbers.size(); i++)
{
outfile << i << ": ";
outfile << numbers[i] << "\t";
if (i % 5 == 0)
{
outfile << std::endl;
}
}
outfile.close();
}
}
Use this in your code
#include <fstream>
ofstream outputFile;
outputFile.open("outputfile.txt");
outputFile << value << endl;
outputFile.close();
One solution is to use ofstream (in "fstream.h", very similar to std::cout):
ofstream out("num.txt");
if (out.is_open() == false)
{
cout << "Error! Couldn't open file!" << endl;
}
else
{
out << "\n";
for (int i = 1; i < 21; i++)
{
out << i << ": ";
out << x[i] << "\t";
if (i % 5 == 0)
{
out << "\n";
}
}
out.close();
}
If you're running your program from the command line, type the following(when you run it) to forward the output to a file:
myApp > num.txt
you can also use the < switch to specify a file to get input from too
You can find more information here.
here is your code with all the changes
now you just need to copy paste (i have made a comment on line i added )
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <fstream>//file stream
using namespace std;
int main() {
int x[21], s;
int j,i;
for (int i = 1; i < 21; i++)
{
cout << setw(11) << i << ": ";
cin >> x[i];
}
for (int i = 1; i < 21; i++)
{
for (int j = i+1; j < 21; j++)
{
if (x[j] < x[i])
{
s = x[j];
x[j] = x[i];
x[i] = s;
}
}
}
ofstream out; //output file stream
out.open("num.txt"); //opening (and creating output file named out
//cout << endl;
for (int i = 1; i < 21; i++)
{
//cout << i << ": ";
out << i << ": "; //printing in output file
// cout << x[i] << "\t";
out << x[i] << "\t"; //printing in output file
if (i % 5 == 0)
{
//cout << endl;
out << endl; //printing in output file
}
}
//getch();
out.close(); //closing output file
return 0;
}

Reading Text File of Floats into a 2D Vector in C++

I have a data file comprised of thousands of float values and I want to read them into a 2D vector array and pass that vector to another routine once it's stored the floats from the file. When I run this code it prints out;
[0][0] = 0, [0][1] = 0, etc.
The data file contains values like;
0.000579, 27.560021, etc.
int rows = 1000;
int cols = 2;
vector<vector<float>> dataVec(rows,vector<float>(cols));
ifstream in;
in.open("Data.txt");
for(int i = 0; i < rows; i++){
for(int j = 0; j < 2; j++){
in >> dataVec[i][j];
cout << "[ " << i << "][ " << j << "] = " << dataVec[i][j] << endl;
}
}
in.close();
It looks to me like the file could not be opened. You did not test for success, so it will plough on regardless. All your values were initialized to zero and will stay that way because every read fails. This is conjecture, I admit, but I'd put money on it. =)
Try this solution, it works according to your specs:
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main(void)
{
ifstream infile;
char cNum[10] ;
int rows = 1;
int cols = 2;
vector<vector<float > > dataVec(rows,vector<float>(cols));
infile.open ("test2.txt", ifstream::in);
if (infile.is_open())
{
while (infile.good())
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < 2; j++)
{
infile.getline(cNum, 256, ',');
dataVec[i][j]= atof(cNum) ;
cout <<dataVec[i][j]<<" , ";
}
}
}
infile.close();
}
else
{
cout << "Error opening file";
}
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
void write(int m, int n)
{
ofstream ofs("data.txt");
if (!ofs) {
cerr << "write error" << endl;
return;
}
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
ofs << i+j << " ";
}
void read(int m, int n)
{
ifstream ifs("data.txt");
if (!ifs) {
cerr << "read error" << endl;
return;
}
vector<float> v;
float a;
while (ifs >> a) v.push_back(a);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
cout << "[" << i << "][" << j << "] = "
<< v[i*n+j] << ", ";
}
int main()
{
write(2,2);
read(2,2);
return 0;
}