C++ pyramid of numbers - c++

I need to write a program where it takes 2 integers from a file. Then it has to make a pyramid from those 2 numbers. It has to look like this:
I've wrote the code and it works as I want to, bet I can't think of a way how make it look a pyramid like.
Here's how it looks when I do it:
And this is my code:
#include <fstream>
using namespace std;
int main(){
ifstream inFile("Duomenys.txt");
ofstream outFile("Rezultatai.txt");
int N,M,smth,suma=0;
inFile >> N >> M;
smth=N;
while(N<=M){
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
suma+=i;
if(i==N){
for(int i=N-1;i>=smth;i--){
outFile<<i<<" ";
suma+=i;
}
}
}
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
inFile.close();
outFile.close();
return 0;
}
So my question would be, how to make it that my answer would be shaped in pyramid like in example?

#include <fstream>
#include <iostream>
#include <iomanip>
#include <assert.h>
using namespace std;
template <class T>
int numDigits(T number)
{
int digits = 0;
while (number) {
number /= 10;
digits++;
}
return digits;
}
int main()
{
ifstream inFile("Duomenys.txt");
ofstream outFile("Rezultatai.txt");
int N,M,smth,suma=0;
inFile >> N >> M;
smth=N;
// assuming positive numbers
assert(N>=0 && M>=0);
// this will be the size of each printed number
int nd = numDigits<int>(M)+1;
while(N<=M){
for(int i=N;i<=M;i++)
outFile << setw(nd) << " ";
for(int i=smth;i<=N;i++){
outFile << setw(nd) << i;
suma+=i;
if(i==N){
for(int i=N-1;i>=smth;i--){
outFile << setw(nd) << i;
suma+=i;
}
}
}
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
inFile.close();
outFile.close();
return 0;
}

First you must compute your second number's digit count. It's so easy. Then you can calculate the depth of concluded pyramid using: (second number- first number)+1. After that you can be sure that in the last row, the max digit count you will have is ((second number - first number)*2+1)*digit count=x of pyramid's head. So you should print the head of pyramid at (x,y)=(x of pyramid's head, ....)

To determine the length of the last row you can either write your output to an std::stringstream and get the length with myStrStream.str().size() (and afterwards print the contents of your string stream to std::cout or your outFile) or you can count the length of all items of the last line separately and then sum then up, including spaces. I think the first approach is simpler.
The easiest approach might be backtracking.

This also depends on the digits that every number have.
Assuming that every number has two digits, is enough to add a certain number of space for each iteration.
This number in your case is 5 during the first iteration, and ends up being zero:
#include <fstream>
using namespace std;
int main(){
ifstream inFile("Duomenys.txt");
ofstream outFile("Rezultatai.txt");
int N,M,smth,suma=0;
inFile >> N >> M;
smth=N;
while(N<=M){
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
suma+=i;
if(i==N){
for(int i=N;i<M;i++)
cout << " ";
for(int i=N-1;i>=smth;i--){
outFile<<i<<" ";
suma+=i;
}
}
}
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
inFile.close();
outFile.close();
return 0;
}
An alternative is to use iomanip's setw, but this case you have to write all numbers in a string and print the whole string each time.

#include<fstream>
using namespace std;
ofstream outFile("output");
void printSpace(int a){
string spaces(a,' ');
outFile<<spaces;
}
int main(){
int N=1,M=11,smth=4,suma=0;
int l=2*(M-N);
while(N<=M){
printSpace(l);
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
suma+=i;
if(i==N){
for(int i=N-1;i>=smth;i--){
outFile<<i<<" ";
suma+=i;
}
}
}
l-=2;
outFile<<endl;
N++;
}
outFile<<endl<<"Skaiciu suma: "<<suma;
outFile.close();
return 0;
}

inFile >> N >> M;
smth=N;
while(N<=M){
for(int position=0;position<(M-N);position++){ // doesn't work if M<N obviously
for(int digit=(smth+position);digit;digit=digit/10){
outFile<<" ";
}
outFile<<" "; // this is to complement the spacer for each digit in your code
}
for(int i=smth;i<=N;i++){
outFile<<i<<" ";
...

Related

Is there a way i can use a text file to operate a program to display the occurrence of numbers in C++?

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream ticket ("numbers.txt");
bool isCovered[99];
int number;
for (int i = 0; i < 99; i++)
isCovered[number] = false;
// Read each number and mark its corresponding element covered
ticket >> number;
while (number != 0)
{
isCovered[number - 1] = true;
ticket >> number;
}
// Check if all covered
bool allCovered = true; // Assumes all covered initially
for (int i = 0; i < 99; i++)
if (!isCovered[i])
{
allCovered = false; //Finds one number not covered
break;
}
return 0;
I know i may have confused you all with the last question i posted but this time i understand the concepts and have an even better question. How can i display the number of occurrences using a txt file in fstream while using C++? And how would i properly use my for and if loops for said problem, thanks?
Update: Got the numbers from the text file to display as well as numbers 1 - 99. But how do i code for the number of occurrences?
#include <fstream>
#include <string>
using namespace std;
int main()
{
int i;
// Open the text file in the system
ifstream infile;
infile.open("numbers.txt");
if(infile.fail())
{
cout << "This file does not work";
}
else{
string s;
while(infile >> s){
cout << s << endl;
}
}
// Display all numbers 1 through 99
for (i = 1; i < 99; i++){
cout << i << endl;
}
}

How to get the average from data.txt file with C++?

Our professor wants us to fix the code which counts the amount of values in a data.txt file and computes their average. Here is the code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
string s;
ifstream f;
int nItems;
double * data;
double sum=0;
vector < double > data2;
double item;
cout <<"File name: ";
cin >> s;
f.open (s.c_str() );
while (! f.eof() )
{
f >> item;
data2.push_back(item);
}
for (int i =0; i < nItems; i++)
{
sum += data[i];
}
cout << "The average is " << sum/nItems <<".\n";
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
His instructions were:
Modify code worked on today so that the average of data in vector < double > data is computed properly. Right now the code just gives you a value which isn't the average.
I tried changing the nItems variable into 12 and that seemed to work, but the goal of the code is to determine nItems and use that to find the average, which I can't seem to figure out.
You use data for which you haven't allocated any memory when you summarise That causes undefined behaviour. You've stored your values in data2. Remove variables you don't need. Also, using namespace std is considered bad practice.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <numeric> // std::accumulate
int main(int, char**) {
std::string filename;
std::cout << "File name: ";
std::cin >> filename;
std::ifstream f(filename); // no need for .c_str()
std::vector<double> data;
double item;
// instead of checking for eof, check if extraction succeeds:
while(f >> item) {
data.push_back(item);
}
// a standard way to sum all entries in a container:
double sum = std::accumulate(data.begin(), data.end(), 0.);
std::cout << "The sum is " << sum << "\n";
// use the containers size() function. it returns the number of items:
std::cout << "The average is " << (sum / data.size()) << "\n";
}
Hey looks like you weren't reading the numbers in from the txt file.
Here I look through the input file once just to count how many numbers there are
so I can make the array.
Then I look through it again to fill the array.
#include <cstdlib>
#include <iostream>
#include <fstream>
// f here stands for find, fstream gives you files
using namespace std;
int main(int argc, char *argv[]) {
string s;
ifstream f;
// input file stream
int nItems;
double * data;
double sum=0;
cout << "File name: ";
cin >> s;
f.open (s.c_str() );
// s.c_str will return a char array equivalent of the string s
nItems=0;
int input =0;
while (f >> input) {//first loop reading through file to count number of items
nItems++;
}
f.close();
data = new double[nItems]; //Make the array
f.open (s.c_str() );//open file for second read
int i=0;
while (f >> input) {//Second loop through file fills array
data[i] = input;
i++;
}
f.close();
for (int i = 0; i < nItems; i++) {
sum += data[i];
}
cout << "The average is " << sum / nItems << ".\n";
cout << endl;
system("pause");
return 0;
}

printing weird symbols to output file, c++

I am writing a code that reads an input file of numbers, sorts them in ascending order, and prints them to output. The only thing printed to output is some really freaky symbols.
Here is my code
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
int i, y, temp, num[20];
char file_nameI[21], file_nameO[21];
ofstream outfile;
ifstream infile;
cout << "Please enter name of input file: ";
cin >> file_nameI;
infile.open(file_nameI);
if (!infile)
{
cout << "Could not open input file \n";
return 0;
}
cout << "Please enter name of output file: ";
cin >> file_nameO;
outfile.open(file_nameO);
if (!outfile)
{
cout << "Could not open output file \n";
return 0;
}
for (i = 0; i < 20; i++)
{
y = i + 1;
while (y < 5)
{
if (num[i] > num[y]) //Correction3
{
infile >> temp;
temp = num[i];
num[i] = num[y];
num[y] = temp;
//y++; //Correction4
}
y++;
}
}
for (i = 0; i < 5; i++)
outfile << "num[i]:" << num[i] << "\n";
return 0;
}
Here is my input
6 7 9 0 40
Here is the output
 „Ô,üþ 54
H|À°ÀzY „Ô,üþ 0
Problems with your code are already mentioned in the comments but again:
First problem is uninitialized elements of num[20] - elements of num have indeterminate values so accessing any of them triggers undefined behavior. You should first read them from the file or at least initialize them to some default value.
The part of code that should most likely do the sorting is just completely wrong. If you'd like to implement your own function for sorting, you can pick up some well-known algorithm like e.g. quicksort - but C++ Standard Library already provides sorting function - std::sort.
Besides obvious mistakes:
You are using char[] - in C++ it's almost always better to use std::string.
Your static array can only store 20 values and you are reading those from a file. You can use std::vector which can grow when you add more elements than its current capacity. It also automatically fixes the problem with uninitialized elements of num[20].
As mentioned in the comments you can organize your code and improve readability by splitting it into functions.
Here you've got it quickly rewritten. This code uses std::string instead of char[], std::vector to store the numbers and std::sort. If there is something you don't understand here, read SO documentation:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> read_file(ifstream& in_file)
{
vector<int> vec;
int value;
while (in_file >> value)
{
vec.push_back(value);
}
return vec;
}
void write_file(ofstream& out_file, const vector<int>& values)
{
for (size_t i = 0; i < values.size(); ++i)
out_file << "value #" << i << ": " << values[i] << '\n';
}
int main()
{
string input_filename, output_filename;
ofstream out_file;
ifstream in_file;
cout << "Please enter name of input file: ";
cin >> input_filename;
in_file.open(input_filename);
if (!in_file)
{
cout << "Could not open input file\n";
return 0;
}
cout << "Please enter name of output file: ";
cin >> output_filename;
out_file.open(output_filename);
if (!out_file)
{
cout << "Could not open output file\n";
return 0;
}
auto numbers = read_file(in_file);
sort(begin(numbers), end(numbers));
write_file(out_file, numbers);
return 0;
}
You might forgot to store values in num array. Just update your code as follows and it will work.
infile.open(file_nameI);
if (!infile){
cout << "Could not open input file \n";
return 0;
} else{
i = 0;
while (infile >> num[i]){
i++;
}
}

Read a .txt file, calculate sum and mean

I have a .txt file which contains numbers and looks like this:
1
2
3
etc
The numbers are unimportant but they all start on a new line.
I want to then find the sum & mean of the numbers in the text file.
Here's what I have so far:
#include<cmath>
#include<cstdlib>
#include<iomanip>
#include<string>
#include<fstream>
using namespace std;
int main(int argc, char * argv[])
{
std::fstream myfile("numbers.txt", std::ios_base::in);
float a;
while (myfile >> a)
{
printf("%f ", a);
}
getchar();
return 0;
int sum(0);
int sumcount(0);
double average(0);
int even(0);
int odd(0);
ifstream fin;
string file_name;
int x(0);
cout<<"numbers.txt";
cin>> file_name;
fin.open(file_name.c_str(),ios::in);
if (!fin.is_open())
{
cerr<<"Unable to open file "<<file_name<<endl;
exit(10);
}
fin>>x;
while (!fin.fail())
{
cout<<"Read integer: "<<x<<endl;
fin>>x;
sum=sum+x;
sumcount++;
if(x%2==0)
even++;
else
odd++;
}
fin.close();
average=(double)sum/sumcount;
cout<<"Sum of integers: "<<sum<<endl;
cout<<"Average: "<<average<<endl;
cout<<"Number of even integers: "<<even<<endl;
cout<<"Number of odd integers: "<<odd<<endl;
return 0;
}
The start loads the numbers but it won't execute the next step.
i have looked at a lot of other code and tried to implement other ideas to solve the problem; however, some people use loops and arrays and other things and I'm not sure which to use.
How can I get my program to find the sum and mean of numbers in the file?
also any other links for help would be appreciated
EDIT: although the numbers are intergers the mean may not be
Here is your working code.
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char * argv[])
{
std::fstream myfile("numbers.txt", std::ios_base::in);
float a = 0;
myfile >> a;
while (!myfile.fail())
{
printf("%f ", a);
myfile >> a; // here you dispay your numbers
}
getchar(); // waiting for input
float sum(0);
int x(0);
int sumcount(0);
double average(0);
int even(0);
int odd(0);
ifstream fin;
string file_name;
cout<<"numbers.txt" << endl;
cin>> file_name; // waiting for enter file name
fin.open(file_name.c_str(),ios::in);
if (!fin.is_open())
{
cerr<<"Unable to open file "<<file_name<<endl;
exit(10);
}
fin >> x;
while (!fin.fail())
{
cout<<"Read integer: "<<x<<endl; // display number again
sum=sum+x;
sumcount++;
if(x % 2==0) // compuing your file statistics
even++;
else
odd++;
fin>>x;
}
fin.close();
average=(double)sum/sumcount;
cout<<"Sum of integers: "<<sum<<endl; // displaying results
cout<<"Average: "<<average<<endl;
cout<<"Number of even integers: "<<even<<endl;
cout<<"Number of odd integers: "<<odd<<endl;
return 0;
}
I have added some minimal alteration to make your program work correctly.
the result
and more
As soon as your main function encounters the statement return 0 it will exit the program and fail to execute the remaining code. This should generally appear only once in your main function, at the end of your code block
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int n=0;
int sum=0,total=0;
fstream file("numbers.txt");
while(file >> n) // or while(cin >> n) to read from stdin, commandline
{
sum += n;
total++;
}
int average = (float) sum/total;
cout<<"sum: " << sum << endl;
cout << "average: " << average << endl;
return 0;
}
#include <iostream>
#include<fstream>
int main()
{
std::ifstream txtFile;
txtFile.open("data.txt");
//TODO: check if the file fails to open.
double tempNum, mean(0.0), sum(0.0), count(0.0);
while (txtFile >> tempNum)
{
sum += tempNum;
++count;
}
mean = sum/count;
std::cout << "mean: " << mean << " sum: " << sum << std::endl;
return 0;
}

Read file from txt

I ve got a txt file with double matrix 50x8. The first two lines contains the array size
50
8
the 50x8 matrix. When i trid to read this file with the above code:
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream infile;
infile.open("C:/Users/zenitis/Desktop/BTHAI_2.3b-src/BTHAI/txtFiles/W1.txt");
double events[50][8];
while (!infile.eof())
{
for(int j=0;j<50;j++)
{
for(int k=0; k<8;k++)
{
infile >> events[j][k];
// infile.get(c
}
}
} //end while
infile.close();
for(int i = 0; i<50; i++){
for(int l=0; l<8; l++){
cout << events[i][l] << " ";
}
cout << "\n";
}
cout << events[0][0];
system("pause");
return 0;
}
Firstly when i print the results the first two elements of the events matrix are the last two of the file. Secondly any idea how to read just the two first elements which is in fact the size of the matrix????
You read the number of rows and columns like this:
int R, C;
infile >> R;
infile >> C;
You do it before the nested loops that read the rest of the file. Then you use the numbers from the file as your end-of-loop targets, rather than hard-coding 50 and 8.