Simple Array Coordinate Display Matching - c++

I am attempting to create an array which takes user input and breaks at 99 99 but the multidimensional array does not stop taking inputted values. Another issue is getting the values to display on the grid down below in the visual representation. If more clarification is needed, please let me know.
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int organisms[22][22];
int rows,
columns;
int input[22][22];
int *output = new int[];
//filling array
for(int i=0;i<22;i++)
{
for(int j=0;j<22;j++)
{
organisms[i][j]=0;
}
}
//column output
cout<<"\t\t\t\t\t\t\t\t\t\t\t\t\tColumn\n\n";
for(columns=1;columns<21;columns++)
{
cout<<"\t"<<columns;
}
cout<<"\n\n\n";
//Row and data output
for(int i=0;i<20;i++)
{
cout<<"Row "<<i+1<<"\t";
for(int j=0;j<20;j++)
{
cout<<organisms[i][j]<<"\t";
}
cout<<endl;
}
cout<<"\n\n\n";
cout<<"Enter each cell in first colony use row space column Enter format, 3 4, for example.\nEnter 99 99 to end entries.\n";
//input of values
cin.ignore(4);
int m=0;
do
{
cin>>input[m][m];
m++;
if(input[m][m]!=99,99)
break;
}while(m<20);
/*
while(input[m][m]!=99,99)
{
cin>>input[m][m];
m++;
}
/*
for(int m=0;m<INT_MAX;m++)
{
cin>>input[m][m];
if(input[m][m]==99)
break;
}
*/
//input array indexing
//output array
cout<<"\n\n\n";
cout<<"\t\t\t\t\t\t\t\t\t\t\t\t\tColumn\n\n";
for(columns=1;columns<21;columns++)
{
cout<<"\t"<<columns;
}
cout<<"\n\n\n";
for(int i=0;i<20;i++)
{
cout<<"Row "<<i+1<<"\t";
cout<<endl;
for(int n=0;n<20;n++)
{
cout<<input[i][n]<<"\t";
}
cout<<endl;
}
cin.get();
cin.get();
return 0;
}

if(input[m][m]!=99,99)
your input is an array of int, 99,99 is not an int. use valid int value, 5555 for example, or simple 99

E.g)
#include <iostream>
#include <iomanip>
#include <utility>
#include <vector>
#include <iterator>
using namespace std;
const size_t size=20;
char table[size][size];
void table_clear(void){
for(int v = 0; v<size; ++v)
for(int h = 0; h<size; ++h)
table[v][h]=' ';
}
void table_put(pair<int, int> p){
int v = p.first;
int h = p.second;
table[v-1][h-1] = '*';//to zero origin
}
void table_disp(){
cout << " ";
for(int i=0; i<size;++i){
cout << setw(3) << i + 1;
}
cout << "\n" << endl;
for(int i=0;i<size;++i){
cout << setw(3) << left << i + 1;
for(int j=0;j<size;++j){
cout << setw(3) << right << table[i][j];
}
cout << endl;
}
}
int main(){
vector<pair<int,int> > v;
pair<int, int> end(99,99);
pair<int, int> rc;
cout << "Enter each cell in first colony use row space column Enter format, 3 4, for example.\n";
cout << "Enter 99 99 to end entries." << endl;
while(true){
int row, column;
cin >> row;
cin >> column;
rc = make_pair(row, column);
if(rc == end)
break;
v.push_back(rc);
}
table_clear();
for(vector<pair<int,int> >::const_iterator iter = v.begin();iter != v.end(); ++iter ) {
table_put(*iter);
}
table_disp();
}

Related

c++ variable sized arrays from Hackerrank with vectors

I wanted to solve a challenge named "Variable sized Arrays" on Hackerrank and I wanted to do that using vectors. The Code I wrote, doesn't work properly and I tried debugging it, but I'm getting nowhere. I'll be grateful for
Here's the challenge:
Consider an n-element array,a, where each index i in the array contains a reference Kito an array of integers (where the value of Ki varies from array to array). See the Explanation section below for a diagram.
Given a, you must answer q queries. Each query is in the format i j, where i denotes an index in array and j denotes an index in the array located at a[i] . For each query, find and print the value of element j in the array at location on a[i]a new line.
Input Format
The first line contains two space-separated integers denoting the respective values of n (the number of variable-length arrays) and q (the number of queries).
Each line of the subsequent lines contains a space-separated sequence in the format k a[i]0 a[i]1 … a[i]k-1 describing the k-element array located at a[i].
Each of the q subsequent lines contains two space-separated integers describing the respective values of i (an index in array a) and j (an index in the array referenced by a[i]) for a query.
Sample Input
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
Sample Output
5
9
So here's my code for this (I'll leave it with the couts for debugging):
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
using std::endl;
int main() {
int numberOfQueries = 0;
int numberOfArrays = 0;
cout << "Enter Nr.Of Arrays followed by Nr.Of Queries:";
cin >> numberOfArrays >> numberOfQueries;
cout << "Nr.Of Arrays: " << numberOfArrays << endl;
cout << "Nr.Of Queries: " << numberOfQueries << endl;
vector<vector<int>>multiArray;
cout << "MultiArray size: " << multiArray.size();
while (numberOfArrays != 0) {
int vsize = 0;
cout << "\nenter array starting by its size: ";
cin >> vsize;
cout << " Size entered is: " << vsize << endl;
vector<int> vec1(vsize);
cout << "Array Size is: " << vec1.size() << endl;
//int element = 0;
while (cin >> vsize) {
cout << "Element is: " << vsize << "\n";
vec1.push_back(vsize);
};
multiArray.push_back(vec1);
numberOfArrays--;
cout << "MultiArray size: " << multiArray.size();
cout << "Nr.Of Arrays: " << numberOfArrays << endl;
};
while (numberOfQueries > 0) {
int i = 0, j = 0;
cout << "\nQuery indexes:";
cin >> i >> j;
cout << multiArray[i][j];
numberOfQueries--;
}
}
while (cin >> vsize) {
cout << "Element is: " << vsize << "\n";
vec1.push_back(vsize);
};
should be something like
for (int i = 0; i < vsize; ++i) {
int elem;
cin >> elem;
cout << "Element is: " << elem << "\n";
vec1.push_back(elem);
}
while (cin >> vsize) isn't going to stop asking for input until you get end of file or an error. But you know how many inputs to expect so code that in a for loop.
My answer.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n,q;
cin >> n >> q ;
vector<int> a[n];
int k;
for(int i = 0; i < n; i++)
{
cin >> k;
for (int j = 0; j < k; j++)
{
int val_a_i_j;
cin >> val_a_i_j;
a[i].push_back(val_a_i_j);
}
};
for (int i = 0; i < q; i++)
{
int a_i, j;
cin >> a_i >> j;
cout << a[a_i][j] << '\n';
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a , b;
cin >> a >> b;
vector<int> arr[a];
for(int i= 0 ; i < a ; i++)
{
int m;
cin >> m;
int o;
for(int j=0;j<m;j++)
{
cin >> o;
arr[i].push_back(o);
}
}
int r,s;
for(int k=1;k<b;k++)
{
cin>>r>>s;
cout <<a[r][s]<< endl;
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n, q;
cin >> n >> q;
vector<int>* a;
a= new vector<int>[n];
int p;
int k;
for (p = 0;p < n;p++) {
cin >> k;
for (int i = 0; i < k; i++) {
int o;
cin >>o;
a[p].push_back(o);
}
}
int r, s;
for (p = 0;p < q;p++)
{
cin >> r >> s;
cout << a[r][s]<<endl;
}
return 0;
}
This problem is about handling vectors of the vector.
int main() {
int n,q;
cin>>n>>q;
vector<vector<int> > a;//creating vectors of vector
int k;
for (int i = 0; i < n; i++)
{
cin >>k;
vector <int> row; // creating vector
for (int j = 0; j < k; j++)
{
int val;
cin>> val;
row.push_back(val);
}
a.push_back(row);
}
for (int l=0; l < q; l++)
{
int i,j;
cin>>i>>j;
// checking boundary conditions
if ((i >= 0 && i < a.size() ) && (j >=0 && j < a[i].size()))
{
cout<<a[i][j]<<endl;
}
}
return 0;
}
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
vector<vector<int>> MultiArry;
vector<int> output;
int n1,n2, q;
int i,j;
cin >> n1 >> q;
MultiArry.resize(n1);
output.resize(q);
for(int i=0;i<n1;i++)
{
cin >> n2;
MultiArry[i].resize(n2);
for(int j=0;j<n2;j++)
{
cin >> MultiArry[i][j];
}
}
for(int ii=0;ii<q;ii++)
{
cin >> i >> j;
output[ii] = MultiArry[i][j];
}
for(int i=0;i<q;i++)
cout << output[i] << endl;
return 0;
}

Finding Max, Min and Mode in c++

So basically I am trying to write a program which accepts an array of integers and then outputs the Max Min and smallest Mode and how many times it occurs.
I have been able to find both max and min and mode, but instead of the smallest mode my code outputs the one that occurs first. And i am not sure how to handle an input with more than one mode.
Below i’ll post my code:
#include
using namespace std;
int main() {
int p,max,min,mode;
cout << "Enter the number of postive integers:"<< endl;
cin >> p;
int pos[p];
cout << "Now enter postive integers!" <<endl;
for(int i=0; i<p; i++) {
cout << "Positive integer " << i+1 << ":";
cin >> pos[i]; }
max =pos[0];
min =pos[0];
for( int i=0; i<p; i++){
if(pos[i]> max) max=pos[i];
if(pos[i]< min) min=pos[i];
}
cout << "Max=" << max << endl;
cout << "Min=" << min << mode= pos[0];
int count[20];
int t=0;
for(int c=0;c<p; c++)
{
for(int d=0;d<p;d++)
{
if(pos[c]==pos[d])
{
count[c]++;
t++;
}
}
int modepos, maxno=count[0];
for(int e=1;e<p;e++)
{
if(maxno<count[e])
{
maxno=count[e];
modepos=e;
}
}
mode=pos[modepos];
if(t==1) {
cout << "There is no positive integer occuring more
than once." << endl;
}
else {
cout <<"The most occuring positive integer is:"<< mode;
cout << "\nIt occurs " << t << " times." << endl;
} return 0; }
there may be simpler and better ways to code this but since i’m a beginner and have only learned loops/conditionals/arrays/variable declaration etc I can only use them in the program, any help will be appreciated.
Do you learn about std::map? The algorithm for counting how many times of an element on an array is very simple with std::map
std::map<long, long > mapFreq;// first: for store value of array pos, second for store value's counter
mapFreq.insert(std::pair<long, long>(pos[0], 1));
for(int i = 1; i < dsize; i++)
{
auto &it = mapFreq.find(pos[i]);
if(it != mapFreq.end())
{
it->second++;
}
else
{
mapFreq.insert(std::pair<long, long>(pos[i], 1));
}
}
Then you can loop through map Freq for what you need:
int number, counter;
for(auto it : mapFreq)
{
if(it.second < counter)
{
number = it.first;
counter = it.second;
}
}
Maybe you can try doing this:
#include <iostream>
#include <algorithm> //for sorting
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++) cin>>a[n];
sort(a,a+n);
int b[a[n-1]];
for(int i=0;i<a[n-1];i++) b[i]=0;
for(int i=0;i<n;i++) b[a[i]]++;
cout<<"Largest number = "<<a[n-1]<<endl;
cout<<"Smallest number = "<<a[0]<<endl;
int rep=0;//repetition
int mode=0;
for (int i=0;i<a[n-1];i++){
if(b[i]>rep){
rep=b[i];// set times of repetition
mode=i;// set new mode
}
}
cout<<"Mode = "<<mode<<endl;
}

Inserting an element into multi dimension vector errors

I'm writing a program where I'm creating a lab with multidimensional vectors. So far I have a constructor that asks the user to input number and sizes of a lab. In the program I'm creating a function called addLab that add a new lab at the specified position with number of computers inputted by user.
While testing the program I make the user input the number of sizes of the lab to be 3 then I tried adding lab 5 to the vector but I get the following output which doesn't compile correctly:
labs: Computer Stations:
1: 1:empty 2:empty 3:empty
2: 1:empty 2:empty 3:empty
3: 1:empty 2:empty 3:empty
Where do you want the lab inserted at?
Here is my header file
#ifndef __grade_weight_calculator__ComputerLabs__
#define __grade_weight_calculator__ComputerLabs__
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class ComputerLabs{
public:
ComputerLabs();
void show_labs();
void add_lab();
private:
vector<vector<string>> labs;
int numoflab;
int numofcomp;
int lab_numba;
int comp_numba;
};
#endif
Here is my implementation cpp file
#include "ComputerLabs.h"
ComputerLabs::ComputerLabs()
{
cout<<"Input the number of labs"<<endl;
cin>>numoflab;
cout<<"Input the size of the labs"<<endl;
cin>>numofcomp;
for (int i=0;i<numoflab; i++){
vector<string> row;
for (int j=0;j<numofcomp; j++)
row.push_back("empty");
labs.push_back(row);
}
}
void ComputerLabs::show_labs()
{
cout<<"labs: "<<"Computer Stations:"<<endl;
int a=0;
int j;
for (int i=0;i<numoflab; i++){
cout<<a+1<<": ";
j=0;
while(j<numofcomp){
cout<<" ";
cout<<j+1<<":"<<labs[i][j];
++j;
}
a++;
cout<<endl;
}
}
void ComputerLabs::add_lab()
{
cout<<"Where do you want the lab inserted at?"<<endl;
numoflab=5;//this makes it add lab 5
vector<string> row;
for(int i=0;i<numofcomp;i++)
{
row.push_back("empty");
}
labs.insert(labs.begin()+4,row);
}
And here is my main.cpp file:
#include "ComputerLabs.h"
int main()
{
ComputerLabs mycomp;
mycomp.show_labs();
mycomp.add_lab();
mycomp.show_labs();
}
I think another error that might be causing this relates to show_labs() function in terms of the algorithm I tried using but im not entirely too sure. Can anyone help me figure out my issues and the solution for fixing it?
The main problem in your code is in the add_lab() function.
void ComputerLabs::add_lab()
{
cout<<"Where do you want the lab inserted at?"<<endl;
// PROBLEM LINE
// Not sure why you needed to do that.
// When the initial value of numoflab is 3,
// numoflabs can be changed to 4 but not 5. If you set it
// to 5 here, you run into problem in show_lab() since
// there aren't 5 rows in your 2D vector.
numoflab=5;//this makes it add lab 5
vector<string> row;
for(int i=0;i<numofcomp;i++)
{
row.push_back("empty");
}
labs.insert(labs.begin()+4,row);
}
Change that function to:
void ComputerLabs::add_lab()
{
cout<<"Where do you want the lab inserted at?"<<endl;
int pos;
cin >> pos;
// Make sure that the input position is valid.
if ( pos > numoflab )
{
cout << "Invalid position." << endl;
return;
}
// Increment numoflab by 1
++numoflab;
std::vector<std::string> tempRow;
for(int i=0;i<numofcomp;i++)
{
tempRow.push_back("empty");
}
labs.insert(labs.begin()+pos, tempRow);
}
General Improvements
You don't need to store numoflab in your class as a member variable. It can be derived from labs.
I see that you have already updated your code so that row is not a member variable of the class any more.
As a matter of good design, it's better to provide the class with its data rather than expecting the class to get the data from stdin or cin.
Here's an updated version of your program.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class ComputerLabs {
public:
ComputerLabs(int numoflab, int numofcomp);
void show_labs();
void add_lab(int pos);
private:
vector<vector<string>> labs;
int numofcomp;
int lab_numba;
int comp_numba;
};
ComputerLabs::ComputerLabs(int numoflab, int numofcomp) : numofcomp(numofcomp)
{
for (int i = 0; i < numoflab; i++){
std::vector<std::string> row;
for (int j = 0; j < numofcomp; j++)
{
row.push_back("empty");
}
labs.push_back(row);
}
}
void ComputerLabs::show_labs()
{
cout << "labs: " << "Computer Stations:" << endl;
int numoflab = labs.size();
for (int i = 0; i<numoflab; i++){
cout << i+1 << ": ";
for (int j = 0; j < numofcomp; j++)
{
cout<<" ";
cout << j+1 << ":" << labs[i][j];
}
cout<<endl;
}
}
void ComputerLabs::add_lab(int pos)
{
int numoflab = labs.size();
if ( pos < 0 || pos > numoflab )
{
cout << "Invalid position." << endl;
return;
}
std::vector<std::string> row;
for(int i=0;i<numofcomp;i++)
{
row.push_back("empty");
}
labs.insert(labs.begin()+pos,row);
}
int main()
{
int numoflab;
int numofcomp;
cout << "Input the number of labs" << endl;
cin >> numoflab;
cout << "Input the size of the labs" << endl;
cin >> numofcomp;
if (!cin )
{
// Deal with error.
}
ComputerLabs mycomp(numoflab, numofcomp);
mycomp.show_labs();
cout << "Where do you want the lab inserted at?" << endl;
int pos;
cin >> pos;
if (!cin )
{
// Deal with error.
}
mycomp.add_lab(pos);
mycomp.show_labs();
}
Update
If you would like sizes of the newly added labs to be different from the sizes of existing labs, you can do the following:
Remove numofcomp as a member variable.
Add another argument to add_lab, numofcomp.
Before calling add_lab, ask the user for the number of components of the lab.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class ComputerLabs {
public:
ComputerLabs(int numoflab, int numofcomp);
void show_labs();
void add_lab(int pos, int numofcomp);
private:
vector<vector<string>> labs;
};
ComputerLabs::ComputerLabs(int numoflab, int numofcomp)
{
for (int i = 0; i < numoflab; i++){
std::vector<std::string> row;
for (int j = 0; j < numofcomp; j++)
{
row.push_back("empty");
}
labs.push_back(row);
}
}
void ComputerLabs::show_labs()
{
cout << "labs: " << "Computer Stations:" << endl;
int numoflab = labs.size();
for (int i = 0; i<numoflab; i++){
cout << i+1 << ": ";
int numofcomp = labs[i].size();
for (int j = 0; j < numofcomp; j++)
{
cout<<" ";
cout << j+1 << ":" << labs[i][j];
}
cout<<endl;
}
}
void ComputerLabs::add_lab(int pos,
int numofcomp)
{
int numoflab = labs.size();
if ( pos < 0 || pos > numoflab )
{
cout << "Invalid position." << endl;
return;
}
std::vector<std::string> row;
for(int i=0;i<numofcomp;i++)
{
row.push_back("empty");
}
labs.insert(labs.begin()+pos,row);
}
int main()
{
int numoflab;
int numofcomp;
cout << "Input the number of labs" << endl;
cin >> numoflab;
cout << "Input the size of the labs" << endl;
cin >> numofcomp;
if (!cin )
{
// Deal with error.
}
ComputerLabs mycomp(numoflab, numofcomp);
mycomp.show_labs();
cout << "Where do you want the lab inserted at?" << endl;
int pos;
cin >> pos;
cout << "Input the size of the lab" << endl;
cin >> numofcomp;
if (!cin )
{
// Deal with error.
}
mycomp.add_lab(pos, numofcomp);
mycomp.show_labs();
}
numoflab = 5; // number of labs increased by 2 (from 3)
for(int i = 0; i < numofcomp; i++)
{
row.push_back("empty");
}
labs.insert(labs.begin() + 3, row); // you added only one lab (or row), (the program expects one more to 5)
You've got to insert one more row, do labs.insert(labs.begin() + 4, row) again for example. (labs.begin() + 3 or labs.begin() + 4 is also perfectly valid.)
You also have a very silly bug in your code, which is using vector<string> row as a member. Now, each time you push_back, row grows in size, but it's never cleared (except at the end of the program). If you printed the whole rows instead of just 3, you'd get this:
labs: Computer Stations:
1: 1:empty 2:empty 3:empty
2: 1:empty 2:empty 3:empty 4:empty 5:empty 6:empty
3: 1:empty 2:empty 3:empty 4:empty 5:empty 6:empty 7:empty 8:empty 9:empty
Very bad. You don't need row to be a member, you can make it local (create and destroy it in every function in which you insert the rows). In the ComputerLabs constructor, it can even be inside the scope of the outer loop:
for (int i = 0; i < numoflab; i++) {
vector<string> row; // constructed every iteration
for (int j = 0;j < numofcomp; j++)
row.push_back("empty");
labs.push_back(row); // row is copied
// row is destroyed
}

Prompt user to enter two 3x3 int arrays and check equivalence

Here is what I have come up with so far... I am so close with literally 1 error left for it to compile.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
const int SIZE = 3;
bool equals(const int m1[][SIZE], const int m2[][SIZE])
{
bool identical = true;
for (int i=0; i < SIZE && identical; i++ )
{
if (m1[i] != m2[i]){
identical = false;
}
}
return identical = true;
}
void printArray(const int m1[], int size)
{
for (int i = 0; i < size; i++)
cout << m1[i] << " ";
}
void printArray2(const int m2[], int size) //not sure if I need this 2nd
{ //void
for (int i = 0; i < size; i++)
cout << m2[i] << " ";
}
int main()
{
string input1, input2;
int const SIZE = 3;
double inputnumber;
int m2[SIZE];
int m1[SIZE];
cout << "Please enter the first array: " << endl;
getline(cin, input1);
stringstream ss (input1);
ss >> inputnumber;
cout << "Please enter the second array: " << endl;
getline(cin, input2);
stringstream si (input2);
si>>inputnumber;
for (int i=0; i< inputnumber ; ++i) {
ss >> m1[i];}
if (equals(m1, SIZE)){
cout << "The two arrays are identical ! ";
}
else{
cout << "The two arrays are NOT identical !";
}
cout << endl;
return 0;
}
Or at least I think that I am close... any help is much appreciated.
My current error is coming up on the IF statement in the main function. I could have more mistakes as I am very very new to C++. Like I said please help me out if you can.
If you just want code here it is , but if you want to practice I recommend you to implement error checking(incorrect format) in this code and to change the loops in my code into functions.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string inp;
cout<<"Please enter an array of numbers in the following form\n"
"(where N's are any numbers) :\n"
"[N N N\nN N N\nN N N"<<endl;
double m1[3][3],m2[3][3];
for(short i=0;i<3;i++){
cout<<"> ";
if(i==0) cout<<"[ ";
getline(cin,inp);
stringstream inps(inp);
for(short j=0;j<3;j++){
inps>>m1[i][j];
}
}// Get the first array
cout<<"Now enter the second array :\n";
for(short i=0;i<3;i++){
cout<<"> ";
if(i==0) cout<<"[ ";
getline(cin,inp);
stringstream inps(inp);
for(short j=0;j<3;j++){
inps>>m2[i][j];
}
}// Get the second one
bool not_equal=false;
for(short i=0; i<3 && !not_equal ;i++)
for(short j=0; j<3 && !not_equal ;j++)
if(m1[i][j]!=m2[i][j])
not_equal=true;// Test equality
if(not_equal)
cout<<"The two arrays you entered are not equal !!"<<endl;
else
cout<<"The two arrays you entered are EQUAL ."<<endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int size = 3;
int m2[size][size];
int m1[size][size];
cout << "Please enter the first array: " << endl;
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
cin >> m1[i][j];
}
}
cout << "Please enter the second array: " << endl;
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
cin >> m2[i][j];
}
}
int flag=1;
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
{
if(m2[i][j]!=m1[i][j])
{
flag=0;
}
}
}
if(flag==1)
{
cout <<"SAME"<<endl;
}
else if(flag==0)
{
cout <<"NOT SAME"<<endl;
}
return 0;
}

how to save the sorted arrays in textfile?

I have a program that sorted arrays how can i save in text file?
for example: the sorted arrays is: 1, 2, 3, 4, 5.
how can i save in text file named. Sorted elements".
I've tried many ways but the sorted array wouldn't save in text file.
I am a newbie so I find it difficult.
here is my code.
#include <iostream>
using namespace std;
int main() {
cout << "Enter number of element:";
int n; cin >> n;
int a[n];
for(int i=0;i<n;i++)
{
cout << "element number " << (i+1) << " : ";
cin >> a[i];
}
int e=1, d=3;
int i, j, k, m, digit, row, col;
int length = sizeof(a)/sizeof(int);
int bmat[length][10];
int c[10];
for(m=1;m<=d;m++)
{
for(i=0;i<10;i++)
{
c[i]=-1;
}
for(i=0;i<length;i++)
{
digit=(a[i]/e)%10;
c[digit]++;
row=c[digit];
col=digit;
bmat[row][col]=a[i];
}
k=-1;
for(i=0;i<10;i++)
{
if(c[i]!=-1)
{
for(j=0;j<=c[i];j++)
{
k++;
a[k]=bmat[j][i];
}
}
}
e=e*10;
}
cout << endl;
cout << "Sorted array:" << endl;
for(int i=0;i<n;i++)
{
cout << a[i] << " , ";
}
cout << endl;
system("pause");
return 0;
}
//Use this code
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
using namespace std;
int main()
{
int n = 0;
cout << "Enter number of element:";
cin >> n;
//Data Structure
std::vector<int> list;
//push back element in vector
for(register int i=0;i<n;++i)
list.push_back(rand()%10 + 1);
//do shuffling before sorting because rand() generates increasing order number
std::random_shuffle(list.begin(),list.end());
std::sort(list.begin(),list.end());
ofstream textfile;
textfile.open ("E:\\example.txt");
for(size_t i= 0;i<list.size();++i)
textfile << list[i] <<" ";
textfile.close();
}
If you can write the sorted array to std::cout, then you can write it to a file. In C++, the console is the same as a file.
Put this at the end of main:
cout << "Sorted array:" << endl;
print_array( std::cout, a, n ); // Show the results to the user.
std::ofstream save( "array.txt" ); // Open a new file (or overwrite).
print_array( save, a, n ); // Save the results for later.
system("pause");
return 0;
}
and put the printing code in a new function, which may be defined before main:
void print_array( std::ostream & s, int * a, int n ) {
for(int i=0;i<n;i++)
{
s << a[i] << " , ";
}
s << endl;
}
#include<iostream>
#include<fstream>
using namespace std;
int compare(int, int);
void sort(int[], const int);
int compare(int x, int y){
return(x > y);
}
void swap(int *x, int *y){
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void display(int array[], int n){
for (int i = 0; i<n; i++) {
cout << array[i] << " ";
}
cout << endl;
}
void writeToFile(int array[], int n){
ofstream myfile;
myfile.open("example.txt");
for (int i = 0; i<n; i++) {
myfile << array[i];
if (i != n - 1){
myfile << ", ";
}
}
myfile.close();
}
void sort(int table[], const int n) {
for (int i = 0; i < n; i++){
for (int j = 0; j < n - 1; j++) {
if (compare(table[j], table[j + 1]))
swap(&table[j], &table[j + 1]);
}
}
}
int main(){
int quantity;
int* tab;
ofstream outfile;
cout << "Enter number of element: ";
cin >> quantity;
tab = new int[quantity];
cout << "Element:\n\n" << endl;
for (int i = 0; i < quantity; i++){
int x = i;
cout << "#" << ++x << ":";
cin >> tab[i];
}
sort(tab, quantity);
cout << "The Sorted Elements are: ";
display(tab, quantity);
writeToFile(tab, quantity);
cout << endl;
getchar();
getchar();
//system("pause");
return 0;
}
in short, add this block to your code:
ofstream myfile;
myfile.open("example.txt");
for (int i = 0; i<n; i++) {
myfile << array[i];
if (i != n - 1){
myfile << ", ";
}
}
myfile.close();
You can use C++ fstream class, since you want to output, you can use ofstream here. You should just replace some "cout" with ofstream instance:
At the beginning of the code state it:
ofstream ofs("./sorted_elem.txt", ofstream::out);
When want to output:
ofs << "Sorted array:" << endl;
for(int i=0;i<n;i++)
{
ofs << a[i] << " , ";
}
ofs << endl;
In C++ you really want to use std::vector or some other nice container for storing arrays of numbers. For writing an array to file you need to open the file and individually write each element to the file (all untested).
#include <fstream>
int main()
{
std::ofstream fp("output.txt");
int data[5]; // todo: fill
for (unsitned i = 0; i < 5; ++i)
{
fp << data[i] << ' ';
}
}
And to read again:
#include <fstream>
int main()
{
std::ifstream fp("output.txt");
// todo: Determine the size of the array or guess it (don't guess it!)
unsigned array_size = 5;
int data[array_size];
int n = 0;
while (fp.good() && n < array_size) fp >> data[n++];
}
But because we are using C++, we can use std::vector:
#include <fstream>
#include <vector>
int main()
{
std::vector<int> me(5); // todo: fill
std::ofstream fp("output.txt");
for (size_t i = 0; i < me.size(); ++i) fp << me[i] << ' ';
// C++11: for (int d : me) fp << d << ' ';
}
And,
#include <fstream>
#include <vector>
int main()
{
std::ifstream fp("output.txt");
std::vector<int> data;
double buf;
while (fp >> buf) data.push_back(buf); // no longer need to guess
}
I think, the copy option was not demonstrated here so far.
Please check this code. (Assuming your vector is ready to use, I've skipped it).
The example uses a C-array and a vector. Please use the later in your code whenever possible. But however, for copy-function both work:
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <fstream>
int main () {
int a[10]={0,1,2,3,4,5,6,7,8,9};
std::vector<int> v; for (int i=0; i<10; ++i)v.push_back(i*10); //0, 10, 20,...
std::ofstream fs_a( "c:/temp/out_a.txt" );
//store space separated
std::copy ( a, a+sizeof(a)/sizeof(a[0]), std::ostream_iterator<int>( fs_a, " ") );
//store coma-separated, as one-liner
std::copy ( v.begin(), v.end() ), std::ostream_iterator<int>( std::ofstream( "c:/temp/out_v.txt" ), ",") );
return 0;
}