How to display results in separate columns in C++ - c++

I'm writing a program for a number theory proof but I have very little experience in writing code.
What i want to do is display all the results of the formula:
Answer = sqrt [4*n]
where;
n = 1,2,3,4,5,6,7,...50
But I want to display the results in 2 groups of columns, i.e.,
I want the 1st column to be the 1st half of n. So as there are 50 iterations, the 1st column will contain the numbers 0 --> 25.
The 2nd column should display the first 25 Answers from the equation.
The 3rd column has the second half of n. i.e., The numbers 26-->50
The 4th column should display the results from the last 25 values of n.
An example of what I'm trying to display is below*:
*(ignore the dots in the below example, they are only there for display purposes only)
n:............Answer:............n:...........Answer:
So far i have the code working but I just can't figure out how to split and display the n-values and Answer-values as I have shown above.
All I can manage to do is display the values in only 2 columns as follows:
n:...........Answer:
This is what I've got so far:
#include <iostream>
#include <iomanip>
#include <cmath> //preprocesser directives
using namespace std; //avoids having to use std:: with cout/cin
int main (int argc, char* argv[])
{
int n;
float Ans;
cout << setw(4) << "n:" << "\t\t" << setw(4) << "Answer:" << "\n" << endl;
for (int n = 0; n<=50; n++)
{
Ans = sqrt ((4)*(n));
cout << setw(4) << n << "\t\t" << setprecision(4) << setw(4) << Ans << endl;
}
cout << "\n\nPress enter to end" << endl;
cin.get();
}
I really have no idea how to split it into 4 separate columns, but I know the \t function must have something to do with it!??
Any help is appreciated!
Thanks

Change your for loop to:
for (int n = 1; n<=25; n++)
{
Ans = sqrt ((4)*(n));
cout << setw(4) << n << "\t\t" << setprecision(4) << setw(4) << Ans << "\t\t";
Ans = sqrt ((4)*(n + 25));
cout << setw(4) << n + 25 << "\t\t" << setprecision(4) << setw(4) << Ans << endl;
}

Loop from 1 to 25 and in the loop body, calculate two results: the one for n and the one for n + 25.
Here is a very simple compilable and runnable example showing you the basic idea:
#include <iostream>
#include <math.h>
int main()
{
for (int n = 1; n <= 25; ++n)
{
std::cout << n << "\t" << sqrt(n) << "\t"
<< (n + 25) << "\t" << sqrt(n + 25) << "\n";
}
}
This may already be sufficient for your needs. However, notice that I've used tabulators. That's easily written but makes correct output depend on tab size, i.e. you may get incorrectly aligned columns on some displays or editors.
One solution for this problem would be to create HTML output, use the <table> element and let a web browser take care of displaying an actual table:
#include <iostream>
#include <math.h>
int main()
{
std::cout << "<table>\n"; // and other HTML stuff
for (int n = 1; n <= 25; ++n)
{
std::cout << "<tr>";
std::cout << "<td>" << n << "</td><td>" << sqrt(n) << "</td><td>"
<< (n + 25) << "</td><td>" << sqrt(n + 25);
std::cout << "</tr>\n";
}
std::cout << "</table>\n";
}
If you are on Windows, then compile this into, say, output.exe, and call it as follows to create an HTML file:
output.exe >output.html
If you want pure text output, things get harder. You'd have to calculate all results in advance, store them in a std::vector, convert each of them to std::strings, look at the strings' sizes, pick the longest, then output all items with appropriate padding spaces. In fact, you'd have to learn a lot of new things for that, which would probably result in one or two additional, more specific questions on Stack Overflow.
Edit: You are using setw(4). Actually, that's another reasonable solution to the problem if you are happy with a fixed width.

This solution solves your problem and has the advantage of solving similar problems where you have to output (x,y) pairs to a four column table. You aren't locked into inputs increasing 1,2,3 etc.
Add this to top of file, with other includes
#include <vector>
Add this to body
cout << setw(4) << "n:" << "\t\t" << setw(4) << "Answer:" << "\n" << endl;
std::vector<double> inputs;
std::vector<double> answers;
for (int n = 0; n<=50; n++){
inputs.push_back(n);
inputs.push_back(sqrt(4*n));
}
for (int n = 1; n<=25; n++){
cout << setw(4) << Inputs[n] << "\t\t" << setprecision(4) << setw(4) << Answers[n] << "\t\t" << setw(4) << Inputs[n+25] << "\t\t" << setprecision(4) << setw(4) << Answers[n+25] << endl;
}

Related

How can you use std::setw() with array output?

I am making a blackjack game in C++, and I am trying to print out the players and dealers cards in addition to their sums, capital and so on. However I'm running into an issue with std::setw() when printing out the vector of cards. Here is a code snippet:
int width = 18;
std::cout << std::left << std::setw(width) << "Your cards:";
std::cout << std::left << std::setw(width * 2) << "arr";
std::cout << std::left << std::setw(width) << "Dealers cards:";
std::cout << "arr2" << std::endl;
std::cout << std::left << std::setw(width) << "Your sum:";
std::cout << std::left << std::setw(width*2) << player.sum();
std::cout << std::left << std::setw(width) << "Dealers sum:";
std::cout << dealer.sum() << std::endl;
Where arr and arr2 is there should be number values like 5 2 6 1, but if I print each element separately the with alignment will break. I think for setw() to work it needs to be one block or string, or else the vertical alignment will mess up once the values change. I tried myString.push_back() for each vector value and then printing that, with no luck. I assume I need to find a way to print the string into one element.
This is what it should look like:
Your cards: 5 7 1 2 Dealers cards: 2 1 7 5
Your sum: 21 Dealers sum: 21
Your capital: 100 Dealers capital: 100
I have found a solution. You can use stringstream to add int values to a string with no errors in conversion, this is how I fixed my code:
#include <sstream>
std::stringstream playerCards{};
for (int i{}; i < player.cards.size(); i++) {
playerCards << player.cards[i] << " ";
}
int width = 18;
std::cout << std::left << std::setw(width) << "Your cards:";
std::cout << std::left << std::setw(width * 2) << playerCards.str();
This way the array will get put into a string and will count as one block, which is what I was looking for.

C++ array structures

I was reading the chapter on structures in my book, and it got me re-modifying a program I already made, but this time using structures which I have never used before; however, after finishing the program, there's one issue I'm not understanding. The output of the program only displays once. It's in a for loop, and yet even though it asks me to input my information three times, it only outputs the first information.
I'm probably just not understanding how arrays in structures work.
An example of my issue is the following.
I have my output on the following loop
for(int counter = 0; counter <size; counter++)
The size is 3, which would mean I'll get the output printed three times; however the answer I'm getting is the same as if I was asking for the following.
Listofnames[0].F_name
When what I actually want is
Listofnames[0].F_name Listofnames[1].F_name Listofnames[2].F_name
However, I don't want to have to write it three times, I did to test it and it actually worked, but is that the only way to do it? Or did I miss something in my program?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct Names
{
string F_name; //Creating structure called Names.
string L_name;
char Mi;
};
struct Payrate
{
double rate;
double hoursworked; //Creating structure called Payrate.
double gross;
double net;
};
int main()
{
double stateTax = 0, federalTax = 0, unionFees = 0, timeHalf = 1.5; //Initializing variables.
const int size = 2; //Array size.
Payrate employee[size]; //Structure variables
Names Listofnames[size];
for (int counter = 0; counter < size; counter++) //Initializing for loop.
{
cout << "What's your first name?: " << endl;
cin >> Listofnames[counter].F_name;
cout << "What's your last name?: " << endl; //Displaying names, and hours worked, rate.
cin >> Listofnames[counter].L_name;
cout << "What is your middle initial?: " << endl;
cin >> Listofnames[counter].Mi;
cout << "How many hours did you work? Please enter a number between 1-50: " << endl;
cin >> employee[counter].hoursworked;
cout << "What is your hourly rate? Please enter a number between 1-50: " << endl;
cin >> employee[counter].rate;
if (employee[counter].hoursworked < 0 || employee[counter].hoursworked >50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].rate < 0 || employee[counter].rate > 50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].hoursworked <= 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * employee[counter].rate; //Calculating gross.
}
else if (employee[counter].hoursworked > 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * (employee[counter].rate * timeHalf); //Calculating gross.
}
stateTax = employee[counter].gross * 0.06;
federalTax = employee[counter].gross * 0.12; //Calculates all the tax fees, and net.
unionFees = employee[counter].gross * 0.02;
employee[counter].net = employee[counter].gross - (stateTax + federalTax + unionFees);
}
cout << "FirstN " << "MI " << "LastName " << "\t" << "Rate " << "HoursWorked " << "TimeHalf " << "StateTax " << "FederalTax " << "UnionFees " << "Gross " << " " << "Net " << endl; //Displays header of output.
cout << "==================================================================================================================" << endl;
for (int counter = 0; counter <= size; counter++)
{
//Output.
cout << Listofnames[counter].F_name << "\t" << fixed << setprecision(2) << Listofnames[counter].Mi << " " << Listofnames[counter].L_name << "\t" << employee[counter].rate << "\t" << employee[counter].hoursworked << "\t" << setw(7) << timeHalf << "\t" << setw(8) << stateTax << setw(12) << federalTax << "\t" << unionFees << "\t" << employee[counter].gross << "\t" << employee[counter].net << endl;
system("pause");
}
}
P.s If you had to re modify this program again, what would you use to simplify it. Asking so I can keep re-modifying, and learn more advanced stuff. Vectors, pointers? Thanks in advance.
You have an array with 3 indexes but your loop is only going upto 2 indexes. Change your for loop to this.
for (int counter = 0; counter <= size; counter++)
Now, this loop will print the all the indexes.
Instead of using a static value you can also use this.
for (int counter = 0; counter < sizeof(Listofnames)/sizeof(Listofnames[0]); counter++)
sizeof(Listofnames)/sizeof(Listofnames[0]) This will give you the total size of your array.
Ideone Link

Issue With Getting the Correct Data (doubles and ints)- C++

So the issue that I'm running into with this piece of code is that if the repetitions exceed 6 then the program crashes. Playing around with it I realized first of all the sums weren't showing up correctly with some couts I placed to test, changing everything to int makes it so the program doesn't crash, but doesn't show the decimals like I need. I am using static cast correctly I thought, but it doesn't seem to add up. I even tried leaving the sum variables as int and keep the average times as a double, but that didn't work either.
I can't figure out for the life of me why it would only work up to 6 repetitions and then crash after that. Here is the piece of code that is causing the issue:
void displayResults(int timingArray1[], int timingArray2[], char sortType1[], char sortType2[], int numRepetitions) {
double sum1 = 0;
double sum2 = 0;
double averageTime1, averageTime2;
int index;
for (index = 0; index < numRepetitions; index++) {
sum1 = sum1 + timingArray1[index];
sum2 = sum2 + timingArray2[index];
}
averageTime1 = (sum1) / static_cast<double>(numRepetitions);
averageTime2 = (sum2) / static_cast<double>(numRepetitions);
cout << "SORTING RESULTS" << endl;
cout << "---------------" << endl;
cout << setw(15) << sortType1 << " Sort " << fixed << setprecision(1) << averageTime1 << " clock ticks on average" << endl;
cout << setw(15) << sortType2 << " Sort " << fixed << setprecision(1) << averageTime2 << " clock ticks on average" << endl;
return;
}

Display data in two columns c++

I am trying to display the same data but in two columns, so after school week 19, the data should be displayed in the columns to the right of the table until the total school weeks is reached i.e. 36. Below is the code:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int const schoolWeeks = 37;
string week[] = { "A", "B", "C", "D" };
int num = 0;
int main()
{
cout << left << setw(9) << setfill(' ') << "Week " << left << setw(9) << setfill(' ')<< "Menu" << left << setw(9) << setfill(' ') << "Week " << "Menu" << endl;
for (int i = 1; i < 20; i++)
{
cout << left << setw(9) << setfill(' ')<< i << week[num] << endl;
num = num + 1;
if (num == 4)
{
num = 0;
}
}
for (int i = 20; i < schoolWeeks; i++)
{
cout << left << setw(9) << setfill(' ') << i << week[num] << endl;
num = num + 1;
if (num == 4)
{
num = 0;
}
}
}
Standard output with std::cout is based on the idea of a stream of data. Remember, it's called "iostream" for a reason. This means once you have written something to std::cout, you simply cannot "go back" a few lines and add something.
Consider piping in a Linux shell or on the Windows command line. It's possible to redirect the output of your program to be the input of another program, which could then do any imaginable thing with it, e.g. sending it over the internet:
myprogram.exe > otherprogram.exe
How could you possibly add something to an already written line in such a scenario?
Considering all of this, it becomes clear that the only viable solution is to know in advance the contents of every line. You cannot wait until line 19 before thinking about the second column, you must do it right away. In other words, first print week 1 and week 19, then week 2 and week 20, then week 3 and week 21, and so on. See the pattern? It's always "week X in column one, week X+18 in column two". And that's pretty much the solution.
Here's a quickly written loop adhering to the style of your existing code:
for (int i = 1; i < 19; i++)
{
cout << left << setw(9) << setfill(' ')<< i << week[num]
<< left << setw(9) << setfill(' ') << " " << (i + 18) << " "
<< left << setw(9) << setfill(' ') << " " << week[num]
<< endl;
num = num + 1;
if (num == 4)
{
num = 0;
}
}
The manipulators like std::setw or std::setfill could probably use some improvement, but the point is that:
The loop only counts from 1 to 18.
The body performs the output for i and for i + 18.

Dynamic alignment issue

When I try to list details of all items, each on a different line
with line numbering, there is alignment issue on it. I want instantly put the close bracket after the line numbering. Thanks.
cout << left
<< setw(20) << " Item Code"
<< setw(50) << "Description"
<< setw(20) << "Quantity on hand"
<< setw(20) << "Cost price"
<< setw(20) << "Selling price(RM)"
<< setw(20) << "Status"
<< setw(20) << "Discount(%)" << endl;
for (int i = 0; i <= 100; i++)//counter - 1; i++)
{
cout << left
<< setw(2) << i + 1 << ")"
<< setw(20) << item[i].getItemCode()
<< setw(50) << item[i].getDescription()
<< setw(20) << item[i].getQuantity()
<< setw(20) << item[i].getCostPrice()
<< setw(20) << item[i].getSellPrice()
<< setw(20) << item[i].getStatus()
<< setw(20) << item[i].getDiscount() << endl;
}
The only way of doing this, as far as I can see, is to walk through the list and find out "how long does this get" for each of the columns, and track what the largest is for each of the columns. Then use those values in the column width.
Strings are easy to find the length of, since they have a length as such. Numbers are harder - basically, you have to either take the approach of dividing it by ten down until it's zero (this means the integer part of floating point numbers - presumably for something like this, you have a fixed number of decimals or use "integeer to represent prices in cents" or some such). You may be able to use the std::tostring to produce as string that has a length too. Or you can use stringstream to output to a string - either individual items, or the whole lot and then count the number of characters between some separator character [that doesn't occur in the normal output, or things go wrong pretty easily!]
Example, using a simple struct:
struct Data
{
int x;
string y;
float z;
}
...
Data d[10];
int maxLen[3] = { 0 };
... // code fills in data with stuff.
for(int i = 0; i < 10; i++)
{
stringstream ss;
ss << left << d[i].x << " " << d[i].y << " " << fixed << setprecision(2) << d[i].z;
// Number of elements = 3.
for(int j = 0; j < 3; j++)
{
string s;
ss >> s;
if (s.length() > maxLen[j])
maxLen[j] = s.legnth;
}
}
...
for(int i = 0; i < 10; i++)
{
cout << left << setw(3) i << ": "
<< setw(maxLen[0]+1) << d[i].x
<< setw(maxLen[1]+1) << d[i].y
<< setw(maxLen[2]+1) << fixed << setprecision(2) << d[i].z << endl;
}