C++:Storing a text file - c++

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

Related

How to reverse this loop cpp

I am trying to get the height of these slashes to be a certain length based on input. So far, I have:
#include <iostream>
using namespace std;
int main() {
int n = 0;
cout << "Enter value: ";
cin >> n;
cout << "You entered: " << n << "\n";
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
cout << '/' << '/';
cout << "\n";
}
}
I need it to then reverse and go back.
It prints:
//
////
//////
If the user entered 3.
It should print:
//
////
//////
////
//
Can anyone lead me in the right direction? I am new to cpp.
You can use a different kind of loop and add a bool variable to track when the program have reached "n". Then, after the program reaches "n", it sets the bool variable to true and starts to substract until i equals 0
Code below, read comments and ask if you have any further questions:
#include <iostream>
using namespace std;
int main()
{
int n = 0;
cout << "Enter value: ";
cin >> n;
cout << "You have entered: " << n << "\n";
int i = 1;
bool reachedN = false; // tells if [i] has reached [n]
while (i != 0)
{
// Print required slashes
for (int j = 1; j <= i; j++)
{
cout << "//";
}
cout << '\n'; // new line
// Add until i == n, then substract
if (i == n)
{
reachedN = true;
}
if (reachedN)
{
--i;
}
else
{
++i;
}
}
}
If you enter 3, the output is the following:
This is one way to achieve that:
#include <iostream>
using namespace std;
int main() {
int n = 0;
cout << "Enter value: ";
cin >> n;
cout << "You entered: " << n << "\n";
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
cout << '/' << '/';
cout << "\n";
}
for (int i = n - 1; i > 0; i--) {
for (int j = 1; j <= i; j++)
cout << '/' << '/';
cout << "\n";
}
}
This is a shorter solution with only two for-loops.
#include <iostream>
using namespace std;
int main()
{
int n = 0;
cout << "Enter value: ";
cin >> n;
cout << "You entered: " << n << "\n";
n = n * 2 - 1;
int r = 0;
for (int j = 0; j < n; j++)
{
if (j > n / 2) r--;
else r++;
for (int i = 0; i < r; i++)
{
cout << '/' << '/';
}
cout << "\n";
}
return 0;
}

How do I combine matrices with files in 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 '>>'.

How to make an output file of n*n matrix,by taking n from the user, with the numbers generated in pairs?

Currently I have a pre-made 6X6 matrix in a text file like this:
2 6 3 1 0 4
4 2 7 7 2 8
4 7 3 2 5 1
7 6 5 1 1 0
8 4 6 0 0 6
1 3 1 8 3 8
and I made a code that is reading from a file i have made. However I want to have user make a grid for themselves (i.e. 3X3 or 10X10). Which then writes to a text file automatically like in similar fashion and then have that read-in instead. It is a basic memory match card game, so I need to have rand() which generates equal pair so the game can be over when every pair in the grid has been found. Thank you so much for your time!
/*Here are the snippets of my code*/
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <fstream>
#include <string>
#include <numeric>
#include <limits>
using namespace std;
//global 2d vectors that are associated with the game
vector<vector<int> > game_grid;
vector<vector<int> > hidden_grid;
vector <vector<int> > guessed;
void initialize_grid() {
ifstream input_file;
input_file.open("grid.txt");
int num;
if (input_file) {
for (int i = 0; i < 6; ++i) {
vector<int> row; // game grid
vector<int> row2; // hidden grid
vector<int> row3; // guessed grid
for (int j = 0; j < 6; ++j) {
if (input_file >> num)
row.push_back(num);
row2.push_back(-1);
row3.push_back(0);
}
game_grid.push_back(row);
hidden_grid.push_back(row2);
guessed.push_back(row3);
}
cout << "Get is ready, Challenger!" << endl << endl;
}
else {
cout << "Womp. File open failed!";
}
return;
}
void print_grid() {
cout << "Game grid" << endl;
cout << " -------------------------" << endl;
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
cout << game_grid[i][j] << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl;
}
void print_hidden_grid(int r1 = -1, int r2 = -1, int c1 = -1, int c2 = -1) {
cout << "Attempt:" << endl;
if (r1 != -1) {
hidden_grid[r1][c1] = game_grid[r1][c1];
}
if (r2 != -1) {
hidden_grid[r2][c2] = game_grid[r2][c2];
}
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
if (hidden_grid[i][j] > -1)
cout << hidden_grid[i][j] << " | ";
else
cout << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl;
if (r1 != -1) {
if (game_grid[r1][c1] == game_grid[r2][c2]) {
guessed[r1][c1] = 1;
guessed[r2][c2] = 1;
cout << "You have a match!" << endl << endl;
}
else {
hidden_grid[r1][c1] = -1;
hidden_grid[r2][c2] = -1;
}
}
cout << endl << endl;
}
void print_current_grid() {
cout << "Current Grid:" << endl;
cout << " -------------------------" << endl;
for (int i = 0; i < 6; ++i) {
cout << " | ";
for (int j = 0; j < 6; ++j) {
if (hidden_grid[i][j] > -1)
cout << hidden_grid[i][j] << " | ";
else
cout << " | ";
}
cout << endl << " -------------------------" << endl;
}
cout << endl << endl;
}
.......
If I well understand you want to auto detect the size of the matrix when you read it ? If yes you can do something like that in initialize_grid :
void initialize_grid() {
ifstream input_file;
input_file.open("grid.txt");
int num;
if (input_file) {
// detect size
int size = 0;
string line;
if (!getline(input_file, line))
return;
istringstream iss(line);
while (iss >> num)
size += 1;
input_file.clear();
input_file.seekg(0);
for (int i = 0; i < size; ++i) {
vector<int> row; // game grid
vector<int> row2; // hidden grid
vector<int> row3; // guessed grid
for (int j = 0; j < size; ++j) {
if (input_file >> num)
row.push_back(num);
row2.push_back(-1);
row3.push_back(0);
}
game_grid.push_back(row);
hidden_grid.push_back(row2);
guessed.push_back(row3);
}
cout << "Get is ready, Challenger!" << endl << endl;
}
else {
cout << "Womp. File open failed!";
}
}
and else where you replace 6 by game_grid.size() (using size_t rather than int to type the indexes)

I can't make the transition to a new line when writing results to a file

I guess that my problem is very trivial, but unfortunately (maybe because I'm really tired) I can't find a solution by myself. Well, my program generates results that I would like to write to successive lines of a text file, because I need to create a graph from them. Unfortunately, in my case, each result is saved in the same line by removing the previous result. Can you help me to improve this code? Thank you.
#include <iostream>
#include <cstring>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <fstream>
using namespace std;
int fp(int x, int y)
{
return (x<=y);
}
void sort_shell(int *tablica, int ilosc)
{
int licznik=0;
int h;
int i;
int temp;
int c=1;
fstream plik;
for (h=1; h<=ilosc/9; h=ilosc/pow(2,h));
c++;
for(; h>0; h /= 3)
{
for (i=h; i<ilosc; i++)
{
int j;
temp = tablica[i];
for (j = i-h ; j>=0; j -=h)
{
if (temp <=tablica[j])
{
tablica[j+h] = tablica[j];
licznik++;
}
else
break;
}
tablica[j+h] = temp;
}
}
/*cout << "\nPo sortowaniu Shellem." << endl;
for(i=0; i<ilosc; i++)
{
cout << tablica[i] << "\t";
}*/
plik.open( "shell.txt", std::ios::in | std::ios::out );
if(plik.good() == true)
{
plik << licznik << "\n";
plik.close();
}
//cout << "\nIlosc operacji :" << licznik << "\n";
}
void sort_hibbard(int x[], int n)
{
int i, j,k, increment, temp,licznik=0;
long swp=0, comp=0;
int val;
fstream plik;
val=log(n+1)/log(2);
increment =pow(2,val)-1;
while (increment > 0)
{
for (i=0; i<increment; i++)
{
for(j=0; j<n; j+=increment)
{
temp=x[j];
for(k=j-increment; k>=0&&temp<x[k]; k-=increment)
{
comp++;
swp++;
x[k+increment]=x[k];
licznik++;
}
x[k+increment]=temp;
swp++;
licznik++;
}
}
comp++;
val--;
if(increment!=1)
increment=pow(2,val)-1;
else
increment = 0;
}
/*cout << "\nPo sortowaniu Hibbardem." << endl;
for(i=0; i<n; i++)
{
cout << x[i] << "\t";
}*/
plik.open( "hibbard.txt", std::ios::in | std::ios::out );
if(plik.good() == true)
{
plik << licznik << "\n";
plik.close();
}
//cout << "\nIlosc operacji :" << licznik << "\n";
}
void sort_sedgewick(int *tablica, int ilosc)
{
int h = 0, i, g, t, j;
int c = 1;
int licznik = 0;
int temp;
fstream plik;
vector <int> tmp;
tmp.push_back(h);
do
{
h = (pow(4,c) + (3 * pow(2,c-1)) + 1); // funkcja z wikipedi O(N^4/3)
tmp.push_back(h);
if(h < ilosc) c++;
}while(h < ilosc);
for(g=ilosc/c;g>0;g/=c)
{
for(i=ilosc-g-1;i>=0;i--)
{
t = tablica[i];
for(j=i+g;(j<ilosc)&&!fp(t,tablica[j]);j+=g)
{
tablica[j-g] = tablica[j];
licznik++;
}
tablica[j-g] = t;
licznik++;
}
}
/*cout << "\nPo sortowaniu SEDGEWICKiem." << endl;
for(i=0;i<ilosc;i++)
{
cout << tablica[i] << "\t";
}*/
plik.open( "sedgewick.txt", std::ios::in | std::ios::out );
if(plik.good() == true)
{
plik << licznik << "\n";
plik.close();
}
//cout << "\nIlosc operacji :" << licznik << "\n";
}
int main()
{
int i, n;
//cout << "Podaj rozmiar tablicy (W tablicy znajda sie liczby od 1 do 100): ";
//cin >> n;
for(n=1000;n<=100000;n+=1000)
{
cout << n << "\n";
int zbior[n];
int prawy = 200;
srand(time(NULL));
//cout << "Przed sortowaniem." << endl;
for (int i = 0; i < n; i++)
{
if (i%2 == 0)
{
zbior[i] = rand()%prawy;
//cout << zbior[i] << "\t";
}
else
{
zbior[i] = rand()%prawy+200;
//cout << zbior[i] << "\t";
}
}
cout << endl;
sort_shell(zbior, n);
sort_hibbard(zbior, n);
sort_sedgewick(zbior, n);
}
return 0;
}
You need to use std::ios::app to append data to a file. You should also keep these files open for the duration of the reporting; you seem to be re-opening them for each iteration.

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