How can I add horizontal space between two functions in C++? - 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.

Related

std::setw() is not giving desired results

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.

Can't align properly using setw manipulator

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

C++ class loop in main

I need help in a simple way of solving a part of my code that i cant seem to make it work.The point of my "assignment" is that everything must try to be in one class.Now the problem i am having is at a part of my code where it is suppose to "print" the n number of products meaning that it displays what you have inputted in the void get() part,but the problem i cant seem to resolve is it only prints the last name,amount,weight of the product and not everything written.
class Class
{
public:
string name;
int n, amount;
float weight;
void market()
{
cout << "Give the number of products you want to get at Market : " << endl;
cin >> n;
}
void get()
{
for (int i = 0; i < n; i++)
{
cout << "Give product name,amount and weight : " << endl;
cin >> name >> amount >> weight;
}
}
void print()
{
cout << "\nProduct display:\n" << endl;
for (int i = 0; i < n; i++)
{
cout << name << " - " << amount << " , " << weight << " kg" << endl;
cout << "------------------------" << endl;
}
};
};
The main part.
int main()
{
Class market;
market.market();
market.get();
market.print();
}
You're actually overwriting name, amount and weight. You have to make use of something similar to std::vector:
class Class {
public:
std::vector<string> names;
// Same for others
When you get them from std::cin you have to push them into the vector:
names.push_back(name);
amounts.push_back(amount);
weights.push_back(weight);
When printing you loop over the vectors:
for (int i = 0; i < n; i++) {
cout << names[i] << " - " << amounts[i] << " , " << weights[i] << " kg" << endl;
cout << "------------------------" << endl;
}
You must use a std::vector<TYPE> (example 1), or array for holding multiple data in a single variable (example 2).
Example 1
Since you've been coding in C++ programming language, it's highly recommended to use std::vector<> for best results.
Consider the class example (read comments too):
int count = 0; // PRIVATE SECTION
char ask;
std::vector<std::string> name;
std::vector<int> amount;
std::vector<float> weight;
std::string tName; // temp variables
int tAmount;
float tWeight;
public:
void market()
{
cout << "WELCOME!" << endl; // nothing's required with vector
}
void get()
{
do {
cout << "Give product name, amount and weight : " << endl;
cin >> tName >> tAmount >> tWeight; // getting temporary variables
name.push_back(tName); // assigning
amount.push_back(tAmount);
weight.push_back(tWeight);
count++;
cout << "Add more? (Y/n): "; // add more? Go on if yes...
cin >> ask;
} while (ask == 'Y' || ask == 'y');
}
void print()
{
cout << "\nProduct display:\n"
<< endl;
for (int i = 0; i < count; i++)
{
cout << name[i] << " - " << amount[i] << " , " << weight[i] << " kg" << endl;
cout << "------------------------" << endl;
}
}
Sample Output
WELCOME!
Give product name, amount and weight :
ABC 12 55.5
Add more? (Y/n): y
Give product name, amount and weight :
SSD 33 43.2
Add more? (Y/n): n
Product display:
ABC - 12 , 55.5 kg
------------------------
SSD - 33 , 43.2 kg
------------------------
Example 2
You can do the same thing just with few modifications, but having static number isn't considered dynamic. You can use arrays for your program as stated below.
Rather than:
string name;
int n, amount;
float weight;
Consider const int MAX = 1024; and use (class variables must be visible only inner the class and nowhere else):
private: // declare on top of the class ("private:" is by default and redundant)
string name[MAX];
int n, amount[MAX];
float weight[MAX];
Edited & working example class:
void get()
{
for (int i = 0; i < n; i++)
{
cout << "Give product name,amount and weight : " << endl;
cin >> name[i] >> amount[i] >> weight[i];
}
}
void print()
{
cout << "\nProduct display:\n"
<< endl;
for (int i = 0; i < n; i++)
{
cout << name[i] << " - " << amount[i] << " , " << weight[i] << " kg" << endl;
cout << "------------------------" << endl;
}
}
Sample Output
Give the number of products you want to get at Market :
2
Give product name,amount and weight :
ABC 25 102
Give product name,amount and weight :
BDE 22 333
Product display:
ABC - 25 , 102 kg
------------------------
BDE - 22 , 333 kg
------------------------

How can I display only cars with 5 seats?

How can I make the program display only cars that have 5 seats, for now no matter what, it shows all cars that I write infos about them, for example if I write in the console that there are 3 cars and give information about them and say that one has 2 seats and the others have 5 after I run the program it still displays all 3 of them. Any idea of how can I display only cars with 5 seats? Can I somehow use the quicksort() function ?
#include <iostream>
using namespace std;
struct Car
{
int no_seats;
int year;
char brand[20];
char color[20];
float horse_power;
};
void read_cars(Car C[], int &n)
{
int i;
cout << "Number of parked cars "; cin >> n;
for(i=1; i<=n; i++)
{
cout << "Brand " ; cin >> M[i].brand;
cout << "The year it was made in " ; cin >> M[i].year;
cout << "Color " ; cin >> M[i].color;
cout << "Power " ; cin >> M[i].horse_power;
cout << "Number of seats " ; cin >> M[i].no_seats;
}
}
void display_cars(Car C[], int n)
{
int i;
for(i=1; i<=n; i++)
{
cout << "Brand " ; cout << M[i].brand << endl;
cout << "The year it was made in " ; cout << M[i].year << endl;
cout << "Color " ; cout << M[i].color << endl;
cout << "Power " ; cout << M[i].horse_power << endl;
cout << "Number of seats " ; cout << M[i].no_seats << endl;
}
}
int main()
{
Car C[50];
int n;
read_cars(M, n);
display_cars(M, n);
return 0;
}
You need to add a condition in the loop:
void display_cars(Car C[], int n)
{
int i;
for(i=1; i<=n; i++)
{
if(M[i].no_seats == 5) // <- like this
{
cout << "Brand " ; cout << M[i].brand << endl;
cout << "The year it was made in " ; cout << M[i].year << endl;
cout << "Color " ; cout << M[i].color << endl;
cout << "Power " ; cout << M[i].horse_power << endl;
cout << "Number of seats " ; cout << M[i].no_seats << endl;
}
}
}
Other notes:
Your n can only go up to 49 - remember that. That also means that you are wasting an element at M[0] (yes arrays are zero based in C++).
Prefer to use std::vector<Car> C over an array of fixed size. A std::vector grows as you push_back more and more elements into it - and it keeps track of the number of contained elements, so you do not need to pass the size of the vector around. C.size() would tell you the number of elements.
void display_cars(const std::vector<Car>& C)
{
std::cout << "There are " << C.size() << " cars in the vector\n";
for(const Car& a_car : C) // a range based for-loop
{
if(a_car.no_seats == 5) // a_car will be a reference to each car in the loop
{
// use "a_car" to display info about one particular car
}
}
}

Different Outputs of an Atoi Converted String-> int

Here is my input file:
Plain Egg
1.45
Bacon and Egg
2.45
Muffin
0.99
French Toast
1.99
Fruit Basket
2.49
Cereal
0.69
Coffee
0.50
Tea
0.75
This is my code. I'm having no problem when people order 8 or 9 items, but as soon as they enter 10 or more items, I get really weird results and not the nicely printed check that I would like to see. For instance, let's say someone orders 8 items and they input "12345678" for their order. I get this:
But if the user inputs that they want let's say 15 items and they order "123456781234567", I get THIS:
Even when they order 10 items, I get just a blank check :/ :
What in the world is happening with my program? Does it have to do with me using c-strings? I want to understand what is going on inside my little computer and understand the way my computer thinks. If you can explain me this in a very simple way (I'm really new so I need something very explanatory with definitions of your fancy words) and some way I can understand, because like I said, I'm really new to computer science. Thank you.
// Local Restaurant: The 5,000 Fed
#include <cmath>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
struct menuItemType {
string menuItem;
double menuPrice;
};
void getData(menuItemType list[]);
string showMenu(menuItemType list[]);
void printCheck(string y, menuItemType list[]);
int main() {
string y;
menuItemType menuList[8];
cout << "Hello and welcome to the 5,000 fed. Your local Long Beach café, "
"whose name is inspired by Jesus' miraculous manifestation "
"of bread to feed the 5k! His disciples helped him in passing out "
"the bread, and so I am here, your waiter, to help you and assist "
"you with your order. ";
getData(menuList);
y = showMenu(menuList);
printCheck(y, menuList);
return 0;
}
void getData(menuItemType list[]) {
string menupricet[8];
ifstream inFile;
inFile.open("menudata.txt");
for (int i = 0; i < 8; i++) {
getline(inFile, list[i].menuItem);
getline(inFile, menupricet[i]);
}
for (int i = 0; i < 8; i++) {
list[i].menuPrice = atof(menupricet[i].c_str());
}
}
string showMenu(menuItemType list[]) {
int amount;
char number;
string reps;
string response = "y";
string total = "";
cout << fixed << setprecision(2);
cout << endl << endl;
cout << "Here is our wonderful menu. I do recommend the french toast, "
"similar to the bread that Jesus ate."
<< endl
<< endl;
for (int i = 0; i < 8; i++) {
cout << i + 1 << ". " << setw(13) << left << list[i].menuItem << setw(8)
<< right << list[i].menuPrice << endl;
}
cout << endl;
cout << "How to order: Write the number you would like and specify how many "
"you want of that item by typing it in multiple times. For instance "
"an input of \"1135777\" means that you want two plain eggs, one "
"muffin, one fruit basket, and three coffees."
<< endl
<< endl;
cout << "How many items are you ordering total?: ";
cin >> amount;
cout << endl;
cout << "Please input your order, and press enter after your order: ";
for (int i = 0; i < amount; i++) {
cin >> number;
total += number;
}
return total;
}
void printCheck(string y, menuItemType list[]) {
int k = 0;
int temp = 0;
double bill = 0;
int newone = 0;
k = atoi(y.c_str());
while (k != 0) {
newone = newone * 10;
newone = newone + k % 10;
k = k / 10;
}
cout << "Thank you for dining at the 5,000 fed. Here's your check:" << endl
<< endl
<< endl;
cout << "_________________" << endl;
while (newone > 0) {
temp = newone % 10;
newone /= 10;
bill += list[temp - 1].menuPrice;
cout << left << setw(15) << list[temp - 1].menuItem << right << setw(5)
<< "|" << list[temp - 1].menuPrice << endl;
}
cout << fixed << setprecision(2);
cout << left << setw(15) << "Amount Due:" << right << setw(10) << "|" << bill
<< endl
<< endl;
}
EDIT:
So someone asked me to paste the output as text instead of images so here are the three outputs:
They order 8 items such as "12345678":
_________________
Plain Egg |1.45
Bacon and Egg |2.45
Muffin |0.99
French Toast |1.99
Fruit Basket |2.49
Cereal |0.69
Coffee |0.50
Tea |0.75
Amount Due: |11.31
They order 15 items such as "123456781234567":
_________________
French Toast |1.99
\365\277\357\376^ޝ-
YW\300\365\277\357\376all\377
\200\367\277\357\376
\370\277\357\376
\227\370\277\357\376
\331\370\277\357\376%\371\277\357\376\262
|0.00
Coffee |0.50
Muffin |0.99
\362\277\357\376x\362\277\357\376x\362\277\357\376x\362\277\357\376Plain Egg33333 |0.00
Plain Egg |1.45
Cereal |0.69
\365\277\357\376^ޝ-YW\300\365\277\357\376all\377\200\367\277\357\376\370\277\357\376\227\370\277\357\376\331\370\277\357\376%\371\277\357\376\262 |0.00
Cereal |0.69
Amount Due: |6.31
They order 10 items such as "1234567812":
_________________
Amount Due: |0.00
The problem in your code is associated with the size of the type int. Here is the solution, you may declare k and new one as unsigned long int so that they can hold up to 4,294,967,295 which still contains only 10 orders.
As a solution, you can use the string y as it is instead of converting to int. So that you can place as many orders as you wish. To traverse through the orders, you can use substr and length function of the string.
Let me re-write the printCheck function for, if I may
void printCheck(string y, menuItemType list[]) {
double bill = 0;
for(int i = 0; i< y.length(); i++)
{
string a = y.substr(i, 1);
int kk = atoi(a.c_str());
bill += list[kk - 1].menuPrice;
cout << left << setw(15) << list[kk - 1].menuItem << right << setw(5)
<< "|" << list[kk - 1].menuPrice << endl;
}
cout << fixed << setprecision(2);
cout << left << setw(15) << "Amount Due:" << right << setw(10) << "|" << bill << endl;
}
I hop this helps. Regards.