std::setw() is not giving desired results - c++

for(int i = 0; i < arr; i++)
{
cout << left << setw(25);
cout << names[i] << " " << age[i];
cout << setw(25);
cout << fname[i] << endl;
}
Here the arrays names,age and fname contain name, age and father's name, respectively.
Output of my code is:
zeel dev 18r k sanghai
amar singh 25r k sanghai
alex pandit 52s n vardhan
After the agecolumn, I want a gap of another 25 columns. How can I do that?
setw() is not working properly.

Related

How can I add horizontal space between two functions in C++?

So I want to output a list of the names and randomly generated numbers. I already did everything else it is just that I do not know how to output it the way I want it to.
I want it to output like this:
ID #: Names:
1 bob
23 rob
44 kanye
Here is what I have so far:
cout << "Would you like to view the archived names and IDs? (Y/N)" << endl;
string archiveInput;
cin >> archiveInput;
if(tolower(archiveInput[0]) == 'y')
{
cout << "ID #: Names: " << endl;
output(ids, names);
}
Here are my functions I used.
void output(const vector<int>& ids)
{
for(int i = 0; i < ids.size(); i++)
{
cout << ids[i] << endl;
}
cout << endl;
}
void output(const vector<string>& names)
{
for(int i = 0; i < names.size(); i++)
{
cout << names[i] << endl; //might have to use endl for list format
}
cout << endl;
}
void output(const vector<int>& ids, const vector<string>& names)
{
cout << output(ids) << " " << output(names); //I thought this would work, im new :(
}
Try to using this method
#include <iostream>
#include <iomanip>
using namespace std;
class Student
{
public:
string studentName;
int studentAge;
int studentMarks;
int admissionYear;
Student(string name, int age, int marks, int year)
{
studentName = name;
studentAge = age;
studentMarks = marks;
admissionYear = year;
}
};
int main()
{
Student studentArray[4] = {Student("Alex", 20, 80, 2018), Student("Bob", 21, 82, 2018), Student("Chandler", 23, 85, 2017), Student("Rose", 18, 89, 2019)};
cout
<< left
<< setw(10)
<< "Name"
<< left
<< setw(5)
<< "Age"
<< left
<< setw(8)
<< "Marks"
<< left
<< setw(5)
<< "Year"
<< endl;
for (int i = 0; i < 4; i++)
{
cout
<< left
<< setw(10)
<< studentArray[i].studentName
<< left
<< setw(5)
<< studentArray[i].studentAge
<< left
<< setw(8)
<< studentArray[i].studentMarks
<< left
<< setw(5)
<< studentArray[i].admissionYear
<< endl;
}
return 0;
}
It will print the below output :
Name Age Marks Year
Alex 20 80 2018
Bob 21 82 2018
Chandler 23 85 2017
Rose 18 89 2019
We have set different widths for each column. The first column width is 10, the second column width is 5, the third column width is 8, and the last column width is 5.
The width is important here. If it is less than the size of its content, the content will overflow.
cout << output(ids) << " " << output(names);
First runs the function output overloaded with ids argument, and afterwards runs the version with the names like so:
for(int i = 0; i < ids.size(); i++)
{
cout << ids[i] << endl;
}
cout << endl;
// returns from first function call
cout << " ";
// enters second function call
for(int i = 0; i < names.size(); i++)
{
cout << names[i] << endl; //might have to use endl for list format
}
cout << endl;
Is how the compiler will run it, which is why your output is underneath each other.
This code is what you want inside the overload with the two arguments:
for(int i = 0; i < ids.size(); i++)
{
cout << ids[i] << " " << names[i] << endl;
}
cout << endl;
However your output will still not quite look like how you want. You have to apply other tricks for that.
This is the reason why your current code behave like that. Look at M Khaidar's answer for the correct way to solve your problem.

Function isn't displaying the desired output from an array argument

First off, If there's any missing information, or you need to know more, please let me know. I'm not an experienced programmer by any means, and this mostly a project I'm working on for a university course.
This is my function definition:
void DispReport(string names[], int IDs[], int grades[][8], int numStudents, int numClasswork, int numQuizzes) {
The job of this function is to display a full table of student names with their ID numbers and grades. At the start, the function will display headers of "Name", "ID", and so on. Then display a continuous line of hyphens as a border underneath. After that it will start extracting and displaying the names, IDs and grades. This is the loop involved (I realize there's a lot of repetitiveness, sorry):
int Qmin, Qmax, CWmin, CWmax, Total;
for(i = 0; i < numStudents; i++){
cout << i+1 << ".";
cout << setw(11) << names[i];
cout << setw(11) << IDs[i];
//Display Quizzes, and Qmin ,Qmax, and Qavg
for(j = 0; j < numQuizzes; j++){
cout << setw(11) << grades[i][j];
if(grades[i][j] < grades[i][j+1])
Qmin = grades[i][j];
else
Qmax = grades[i][j];
};
cout << setw(11) << Qmin;
cout << setw(11) << Qmax;
cout << setw(11) << (Qmin + Qmax)/2;
//Display Classwork, and CWmin, CWmax, and CWavg
for(j = numQuizzes; j < (numQuizzes + numClasswork); j++){
cout << setw(11) << grades[i][j];
if(grades[i][j] < grades[i][j+1])
CWmin = grades[i][j];
else
CWmax = grades[i][j];
};
cout << setw(11) << CWmin;
cout << setw(11) << CWmax;
cout << setw(11) << (CWmin + CWmax)/2;
};
Running this loop results in nothing, however. It runs once, outputting the very first line, "1.", pauses for a second, then the program terminates. Nothing. I checked to ensure that the function had actually receive the arrays I passed to it, through cout << names[different indexes to check different names] and it was all there. The loop however, wouldn't display them, and I'm not getting any error messages. Any ideas?

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.

formatting vector output using iomanip

I'm having some trouble here. I have a file that looks like this (here's a snippet)
Sophia F 22158
Emma F 20791
Isabella F 18931
Jacob M 18899
Mason M 18856
Ethan M 17547
and I want to put each name, and the name's respective number into seperate vectors. For example, I would have 4 vectors:
1 for women's names and 1 for women's numbers, and the same for men's and men's numbers. (so 4 total)
I have this code, which will go through the file and pull out these elements and put them in vectors.
for (int i = 0; i < numTimes; i++) {
getline (inputFile, inputLine);
ss.str(inputLine); //ss is a string stream
ss >> name >> gender >> popularity;
if (gender == 'M') {
mNames[i] = name;
mFrequency[i] = popularity;
} else if (gender == 'F') {
fNames[i] = name;
fFrequency[i] = popularity;
}
ss.clear();
}
and I use this method to print it out:
cout << counter << " Most Popular Baby Names" << endl << endl;
cout << left << setw(15) << "Girls" ;
cout << right << setw(9) << "Frequency" <<" ";
cout << left << setw(15) << "Boys";
cout << right << setw(9) << "Frequency" << endl;
for (int i = 0; i < counter; i ++) {
cout << left << setw(15) << fNames[i] ;
cout << right << setw(9) << fFreq[i] <<" ";
cout << left << setw(15) << mNames[i];
cout << right << setw(9) << mFreq[i] << endl;
{
but then I get this output:
http://i.stack.imgur.com/2x0ta.png
But I would like for it to be like this:
http://i.stack.imgur.com/OSIX9.png
So I'm thinking I either need to go through before I print and remove all the whitespace/0's in these vectors, or I need to check while I'm printing out. Does anyone have any pointers?
Solved, thanks guys.
I used two separate while loops, one for each set of arrays. In between them I reset the ifstream back to the beginning. This way, it goes through until each vector has 5 non-zero elements.

C++ - Unwanted characters printed in output file

This is the last part of the program I am working on. I want to output a tabular list of songs to cout. And then I want to output a specially formatted list of song information into fout (which will be used as an input file later on).
Printing to cout works great. The problem is that tons of extra character are added when printing to fout.
Any ideas?
Here's the code:
void Playlist::printFile(ofstream &fout, LinkedList<Playlist> &allPlaylists, LinkedList<Songs*> &library)
{
fout.open("music.txt");
if(fout.fail())
{
cout << "Output file failed. Information was not saved." << endl << endl;
}
else
{
if(library.size() > 0)
fout << "LIBRARY" << endl;
for(int i = 0; i < library.size(); i++) // For Loop - "Incremrenting i"-Loop to go through library and print song information.
{
fout << library.at(i)->getSongName() << endl; // Prints song name.
fout << library.at(i)->getArtistName() << endl; // Prints artist name.
fout << library.at(i)->getAlbumName() << endl; // Prints album name.
fout << library.at(i)->getPlayTime() << " " << library.at(i)->getYear() << " ";
fout << library.at(i)->getStarRating() << " " << library.at(i)->getSongGenre() << endl;
}
if(allPlaylists.size() <= 0)
fout << endl;
else if(allPlaylists.size() > 0)
{
int j;
for(j = 0; j < allPlaylists.size(); j++) // Loops through all playlists.
{
fout << "xxxxx" << endl;
fout << allPlaylists.at(j).getPlaylistName() << endl;
for(int i = 0; i < allPlaylists.at(j).listSongs.size(); i++)
{
fout << allPlaylists.at(j).listSongs.at(i)->getSongName();
fout << endl;
fout << allPlaylists.at(j).listSongs.at(i)->getArtistName();
fout << endl;
}
}
fout << endl;
}
}
}
Here's a sample of the output to music.txt (fout):
LIBRARY
sadljkhfds
dfgkjh
dfkgh
3 3333 3 Rap
sdlkhs
kjshdfkh
sdkjfhsdf
3 33333 3 Rap
xxxxx
PayröÈöè÷÷(÷H÷h÷÷¨÷È÷èøø(øHøhøø¨øÈøèùù(ùHùhùù¨ùÈùèúú(úHúhúú¨úÈúèûû(ûHûhûû¨ûÈûèüü(üHühüü¨üÈüèýý(ýHýhý
! sdkjfhsdf!õüöýÄõ¼5!
sadljkhfds!þõÜö|ö\
þx þ  þÈ þð ÿ ÿ# ÿh ÿ ÿ¸ ÿà 0 X ¨ Ð ø
enter code here
enter code here
Most likely, one of your methods returns an improper char * string (not null terminated).
Edit: actually, not just one: getPlaylistName(), getSongName() and getArtistName().