Can't align properly using setw manipulator - c++

I can't align the output of my program.
I want to keep the same names and get the right spacing.
The code is provided below.
I also tried using left but it still does not work.
The output I am expecting:
The output I am getting:
//taking name and votes recieved
for (i = 0; i < 5; i++)
{
cout << "Enter last name of candidate " << (i + 1) << ": ";
cin >> names[i];
cout << "Enter votes recived by " << names[i] << ": ";
cin >> votes[i];
}
//calculating total votes
for ( i = 0; i < 5; i++)
{
total = total + votes[i];
}
//calculating percentage of total votes for each candidate
for ( i = 0; i < 5; i++)
{
percent_of_total[i] = (votes[i] / total) * 100.0;
}
//checking winner
winner = names[0];
int most = 0;
for ( i = 0; i < 5; i++)
{
if (votes[i] > most)
{
most = votes[i];
winner = names[i];
}
}
cout << fixed << setprecision(2);
//dislaying
cout << "Candidte" << setw(20) << "Votes Recieved" << setw(20) << "% of Total Votes";
for (i = 0; i < 5; i++)
{
cout << endl;
cout << names[i] << setw(20) << votes[i] << setw(20) << percent_of_total[i];
}
cout << endl;
cout << "Total" << setw(20) << total;
cout << endl << "The winner of the Election is " << winner << ".";
return 0;
}

setw needs to be invoked before the field you wish to apply the fixed length to. That includes the names. If you want to keep the names left aligned you can use
std::cout << std::left << std::setw(20) << name /*<< [...]*/;
As a side note you should avoid using using namespace std;. The reason is that std contains a lot of names and you might use other libraries using the same names or use them yourself. std is fairly short and doesn't clutter up the code too much. A viable alternative is to use
using std::cout;
using std::cin;
using std::endl;
using std::setw;
using std::left;
// etc
for all the names you want to use.
another alternative is to invoke using namespace std in the function you want to use the std namespace.
#include <iostream>
void f()
{
using namespace std;
cout << "f() call" << endl;
}
int main()
{
// std not being used here by default
f();
return 0;
}

Related

How do I align my output when a word is too long?

I am trying to create a program where the user enters 5 candidates for an election along with their number of votes. The program's output creates a table where it shows each candidates name, their votes, percentage of votes, and the winner of the election. My code is below and a sample of the output is in a picture that I have uploaded.
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <conio.h>
using namespace std;
const int numofcandidates = 5;
// declare variables and arrays
string candidateName[numofcandidates] = { "" };
int candidatevotes[numofcandidates];
float totalvotepercentage;
// declare methods
void takeNameandVote();
void printTable();
int main()
{
takeNameandVote();
printTable();
}
void takeNameandVote()
{
for (int i = 0; i < numofcandidates; i++)
{
cout << "Enter last name for candidate " << i + 1 << ": ";
cin >> candidateName[i];
cout << "Enter number of votes for this candidate: ";
cin >> candidatevotes[i];
}
}
void printTable()
{
// to set up % of total votes
int totalvotes = 0;
for (int i = 0; i < numofcandidates; i++)
{
totalvotes += candidatevotes[i];
}
cout << "Candidate\tVotes Received\t\t" << '%' << " of Total Votes" << endl;
for (int i = 0; i < numofcandidates; i++)
{
cout << candidateName[i] << '\t' << setw(18) << candidatevotes[i] << "\t" << fixed << showpoint << setprecision(2) << setw(16) << (candidatevotes[i] / (double)totalvotes * 100) << endl;
}
cout << "Total\t\t" << setw(10) << totalvotes << endl;
cout << endl;
}
Remove all \ts and only use std::setw:
std::cout << std::left << std::setw(18) << candidateName[i]
<< std::right << std::setw(8) << candidatevotes[i] << ...

Adding all value to total in for loop

I'm new to coding. I wrote the below code in C++ and I am not allow to use array.
You will create a console C++ program that uses a nested loop to enter each archer's individual end scores and then displays the total score for each archer.
I am stuck at how to calculate the total end score:
#include <iomanip>
using namespace std;
int main()
{
int Rounds = 4;
int Archers = 3;
int endScore ;
int average;
for (int a = 1; a <= Archers ; a++)
{
cout << endl << "Number " << a << " score" << endl;
int tEndScore = 0 ;
for(int i=1; i <=Rounds ; i++)
{
cout << "Round " << i << " : " ;
cin >> endScore;
while(cin.fail())
{
cout << endl << "not enter an integer " << endl ;
cout << "Please enter an integer ";
cin >> endScore;
}
tEndScore += endScore;
}
cout << endl << "The total score for 4 ends of Archer Number " << a << " is " << tEndScore << endl;
average =(double) tEndScore/Rounds;
cout << setiosflags(ios::fixed) << setprecision(2) << endl << "The average score of 4 ends of Archer Number " << a << " is " << average << endl;
}
}
This is the result after running. It will only use the last value I entered as tEndScore:
You need to shift tEndScore =+ endScore; this line inside the second for loop as
for(int i=1; i <=Rounds ; i++)
{
...
...
tEndScore += endScore;
}
And it will be a good practice (And mandatory for your code...) to initialize the tEndScore for each player as
for (int a = 1; a <= Archers ; a++)
{
tEndScore = 0;
endScore = 0;
average = 0;
...
...
}
You need to replace totalEndScore to tEndScore and totalRounds to Rounds.

Multiplying elements in array not working in c++?

I am trying to make a simple program in c++ that takes the price and number of items purchases, stores it in arrays, and then outputs the totals for each item in a tabular format. However, when I multiply the numbers in my code, I get totally strange answers! Can someone please enlighten me as to what's going on?
Code:
#include <iostream>
using namespace std;
int main(int argc, _TCHAR* argv[]) {
float price[4], tot[4];
int amt[4];
cout << "Please enter the price and amount of 4 items:\n";
for (int i = 0; i<4; i++) {
cout << "Price of item " << i + 1 << ": ";
cin >> price[i];
cout << "Amount of item " << i + 1 << ": ";
cin >> amt[i];
if (price[i] <= 0 || amt[i] <= 0) {
cout << "Invalid Input Entry!\n";
break;
}
tot[i] = price[i] * amt[i]; // I can't really see how I could have messed this up...
}
cout << "Total\t\tPrice\t\tAmount\n";
cout << "-----\t\t-----\t\t------\n";
for (int i = 0; i < 4; i++) {
cout << "$" << fixed << cout.precision(2) << tot[i] << "\t\t$" << price[i] << "\t\t" << amt[i] << endl;
}
system("pause");
return 0;
}
Output:
The problem is that you are outputting the return value of cout.precision(2) (which returns the previous precision, in this case 6 initially and then 2 afterwards) in front of each total price.
You need to either:
not pass the return value of cout.precision() to operator<<:
cout << "$" << fixed;
cout.precision(2);
cout << tot[i] << ...
or, call precision() one time before entering the loop:
cout.precision(2);
for (int i = 0; i < 4; i++) {
cout << "$" << fixed << tot[i] << "\t\t$" << price[i] << "\t\t" << amt[i] << endl;
}
use the std::setprecision() stream manipulator instead of calling cout.precision() directly:
#include <iomanip>
for (int i = 0; i < 4; i++) {
cout << "$" << fixed << setprecision(2) << tot[i] << "\t\t$" << price[i] << "\t\t" << amt[i] << endl;
}
or
#include <iomanip>
cout << setprecision(2);
for (int i = 0; i < 4; i++) {
cout << "$" << fixed << tot[i] << "\t\t$" << price[i] << "\t\t" << amt[i] << endl;
}
On a side note, you should not use \t characters to control the formatting of your table. Use stream manipulators like std::setw(), std::left, etc instead:
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
const int maxItems = 4;
string moneyStr(float amount)
{
ostringstream oss;
// in C++11 and later, you can replace this with std::put_money() instead:
// http://en.cppreference.com/w/cpp/io/manip/put_money
//
// oss << showbase << put_money(amount);
oss << "$" << fixed << setprecision(2) << amount;
return oss.str();
}
int main(int argc, _TCHAR* argv[])
{
float price[maxItems], tot[maxItems];
int amt[maxItems];
int cnt = 0;
cout << "Please enter the price and amount of " << maxItems << " items:" << endl;
for (int i = 0; i < maxItems; ++i)
{
cout << "Price of item " << i + 1 << ": ";
cin >> price[i];
cout << "Amount of item " << i + 1 << ": ";
cin >> amt[i];
if (price[i] <= 0 || amt[i] <= 0) {
cout << "Invalid Input Entry!" << endl;
break;
}
tot[i] = price[i] * amt[i];
++cnt;
}
cout << left << setfill(' ');
cout << setw(16) << "Total" << setw(16) << "Price" << setw(16) << "Amount" << endl;
cout << setw(16) << "-----" << setw(16) << "-----" << setw(16) << "------" << endl;
for (int i = 0; i < cnt; i++) {
cout << setw(16) << moneyStr(tot[i]) << setw(16) << moneyStr(price[i]) << setw(16) << amt[i] << endl;
}
system("pause");
return 0;
}
Live Demo

Not outputting the calculation, just 0

I have my code here and it runs, however, when I try to output the percentage it just outputs 0, I've spent a long time trying to figure out what I'm missing and I'm clueless. Basically I'm trying to output the percent of votes for each candidate out of total votes. Any help would be appreciated. Here is my output;
Output display Also, im aware that the winner loops through every user until it reaches the end for some reason, still trying to work out the kinks.
Here is my code -
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class candidatesElection
{
public:
string last;
float votePercent;
void winnerOfElection();
void outputDis();
int total = 0;
};
int main()
{
string lastName[5];
int amountOfVotes[5];
double percentTotal[5];
int total = 0;
int winnerNo = 0;
int winningCandidate;
string winningName;
for (int i = 0; i < 5; i++)
{
cout << "Enter the last name of the Candidate: " << endl;
cin >> lastName[i];
cout << endl;
cout << "Enter the votes received by the Candidate: " << endl;
cin >> amountOfVotes[i];
total += amountOfVotes[i];
cout << "Total number of votes is: " << total << endl;
}
for (int i = 0; i < 5; i++)
{
if (amountOfVotes[i] > amountOfVotes[winnerNo]) winnerNo = i;
amountOfVotes[i] = amountOfVotes[winnerNo];
}
for (int i = 0; i < 5; i++)
{
percentTotal[i] = (amountOfVotes[i] / total) * 100.0; // need to make it floating point
}
void outputDis();
{
cout << endl << left << setw(25) << "Candidate" << right << setw(25) << "Votes Received" << setw(25) << "% of Total Votes" << endl;
for (int i = 0; i < 5; i++)
cout << endl << left << setw(25) << lastName[i] << right << setw(25) << amountOfVotes[i] << setw(25) << percentTotal[i] << endl;
cout << endl << left << setw(25) << "Total" << right << setw(25) << total << endl;
for (int i = 1; i < 5; i++)
{
int winHigh = amountOfVotes[0];
string win = lastName[0];
if (amountOfVotes[i] > winHigh)
{
winHigh = amountOfVotes[i];
win = lastName[i];
}
cout << "The Winner of the Election is " << win << endl;
}
}
system("pause");
};
The coefficient amountOfVotes[i] / total in (amountOfVotes[i] / total) * 100.0 is evalated in integer arithmetic: i.e. any fraction is discarded.
So you end up with 0 * 100 for all cases where amountOfVotes[i] is less than total.
The solution is to rearrange the formula to 100 * amountOfVotes[i] / total;, or, even better 100.0 * amountOfVotes[i] / total; which will force evaluation in double precision floating point - you are in danger of overflowing an int which, on some systems, can have an upper limit as low as 32767.
That's not immediately obvious even when using a line-by-line debugger. But do use that debugger to work out the other "kinks".

Setiosflags is not recognized

I'm trying to compile this but I get the error error: ‘setioflags’ was not declared in this scope which sounds like its trying to recognize it as a variable. This is an example I copied straight from my textbook, checked it over several times and can't find an error. Am I overlooking something? I'm on a mac if that makes a difference, I know the <conio.h> library doesn't work because of that, but <iomanip> is recognized
#include <iostream>
#include <iomanip>
using namespace std;
const int DISTRICTS = 4;
const int MONTHS = 3;
int main() {
int d, m;
double sales[DISTRICTS][MONTHS];
cout << endl;
for(d = 0; d < DISTRICTS; d++)
for(m = 0; m < MONTHS; m++)
{
cout << "Enter sales for district " << d+1;
cout << ", month " << m+1 << ": ";
cin >> sales[d][m];
}
cout << "\n\n";
cout << " Month\n";
cout << " 1 2 3";
for(d = 0; d < DISTRICTS; d++)
{
cout << "\nDistrict " << d+1;
for(m = 0; m < MONTHS; m++) // Display array values
cout << setiosflags(ios::fixed) // Not exponential
<< setioflags(ios::showpoint) // Always use poin
<< setprecision(2) // Digits to right
<< setw(10) // Field width
<< sales[d][m]; // Get number from array
} // end for(d)
cout << endl;
return 0;
}
You're looking for setiosflags. Note the extra s in there. Your spelling is different on the second call.