Loop isn't printing expected results - c++

I'm trying to prompt the user for items and the quantity of those items respectively. But when I run the program, it correctly displays the elements in the first vector, and not the elements in the second vector.
#include <iostream>
#include <vector>
using namespace std;
int main(){
// Declaring vectors
vector <string> items{};
vector <int> quantity{};
cout << "Enter name of items." << endl;
// Read input to vectors
for(int i{1}; i <= 3; ++i){
string item{};
cin >> item;
items.push_back(item);
}
cout << "Enter quantity of each item." << endl;
for(int i{1}; i <= 3; ++i){
int num{};
cin >> num;
quantity.push_back(num);
}
// Display data
for(auto item: items){
int i{0};
cout << "Item: " << item << " - " << "Quantity: " << quantity.at(i) << endl;
++i;
cout << "--------------------" << endl;
}
return 0;
}
output
Enter name of items.
meat fish milk
Enter quantity of each item.
10 20 30
Item: meat - Quantity: 10
--------------------
Item: fish - Quantity: 10
--------------------
Item: milk - Quantity: 10
--------------------
I tried printing out quantity.at(1) and it correctly displays 20, I apologize in advance if I missed out on something obvious. I'm very new to the language.

You are always setting i equal to the 0th element. instead move the creation of i to be outside the loop:
int i{0};
for(auto item: items){
cout << "Item: " << item << " - " << "Quantity: " << quantity.at(i) << endl;
++i;
cout << "--------------------" << endl;
}

You can fix it by bringing the "i" variable out of the last iteration

Related

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

Formatting output (inputted by the user) in columns

I am working on a shopping cart project, and I want to print out the user input like the following output. I don't know how to use setW and right/left keywords, when it comes to the user decides what the output is going to be like. So when they enter different inputs in length, for example setW(20) does not work for them all.
Here is your order:
----------------------------------------------------------------
Name Unit_Price Quantity
T-shirt $19.99 2
Sweater $39.99 1
iphone_case $25.5 3
Towel $9.99 5
The total charge is $206.42
----------------------------------------------------------------
This is the display function:
ostream& operator <<(ostream& os, Item& source) {
os << source.getName() << setw(18)
<< source.getPrice() << setw(20) << source.getQuantity() << endl;
return os;
}
And this is the output I get with this:
Here is your order:
----------------------------------------
NAME PRICE QUANTITY
tshirt 19.99 2
sweater 39.99 1
iphone_case 25.5 3
towel 9.99 5
The total price of the order is 206.42
----------------------------------------
And here is my main.cpp
#include "ShoppingCart.h"
#include "Item.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
cout << endl << endl << "Welcome to XXX SHOPPING CENTER" << endl;
Item items[10];
ShoppingCart<Item> cart;
char userAnswer;
cout << "Enter the item you selected as the following order:\nname unitPrice quantity\n"
<< "(Name can not contain any space. Otherwise errors happen!)" << endl;
cin >> items[0];
cart.add(items[0]);
cout << "Want to continue? y/n" << endl;
cin >> userAnswer;
int index = 1;
while(userAnswer == 'y' || userAnswer == 'Y') {
cout << "Enter the next item:" << endl;
cin >> items[index];
cart.add(items[index]);
cout << "Want to continue? y/n" << endl;
cin >> userAnswer;
index++;
}
// Display the summary of the orders
cout << endl << "Here is your order:" << endl;
// "--------------------------------------------------------------------"
for(int i=0; i < 40; i++)
cout << "-";
cout << endl << "NAME" << setw(18) << "PRICE" << setw(20) << "QUANTITY" << endl;
for(int i=0; i < cart.getCurrentSize(); i++) {
cout << items[i];
}
cout << endl << "The total price of the order is " << cart.getTotalPrice() << endl;
// "---------------------------------------------------------------------"
for(int i=0; i < 40; i++)
cout << "-";
cout << endl;
return 0;
}
The strategy you are using does not make sense to me. Here's one way to get the desired output:
Use 20 characters for the first column and make sure that it is output with left aligned text.
Use 10 characters for the second and third columns, and make sure they are output with right aligned text.
Use std::left and std::right to control text alignment.
Here's a simplified program that demonstrates the idea.
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
struct Item
{
std::string name;
double price;
int quantity;
};
std::ostream& operator<<(std::ostream& out, Item const& item)
{
// First column
out << std::left << std::setw(20) << item.name;
// Second and third columns
out << std::right << std::setw(10) << item.price << std::setw(10) << item.quantity;
return out;
}
void printLine(std::ostream& out)
{
for(int i=0; i < 40; i++)
out << "-";
out << std::endl;
}
int main()
{
std::vector<Item> items;
items.push_back({"tshirt", 19.99, 2});
items.push_back({"sweater", 39.99, 1});
items.push_back({"iphone_case", 25.50, 3});
items.push_back({"towel", 9.99, 5});
printLine(std::cout);
// First column
std::cout << std::left << std::setw(20) << "NAME"
// Second and third columns
std::cout << std::right << std::setw(10) << "PRICE" << std::setw(10) << "QUANTITY" << std::endl;
// The items
for(int i=0; i < 4; i++) {
std::cout << items[i] << std::endl;
}
printLine(std::cout);
}
Output:
----------------------------------------
NAME PRICE QUANTITY
tshirt 19.99 2
sweater 39.99 1
iphone_case 25.5 3
towel 9.99 5
----------------------------------------

Sorting multiple linked arrays in C++ [duplicate]

This question already has answers here:
Sorting two corresponding arrays [duplicate]
(4 answers)
Closed 6 years ago.
Consider the following list:
Name Price(per kg) Weight(in kg)
rice1 40 20
rice2 50 27
rice3 35 24
I want all the rice types sorted according to their value. So, I sort them.
new sorted price: 35 40 50
Now i print them and the output as below:
Name Price Weight
rice1 35 20
rice2 40 27
rice3 50 24
But this is not what I wanted. I wanted it to print like this:
Name Price Weight
rice3 35 24
rice1 40 20
rice2 50 27
so, the problem is I'm getting the the value in the sorted list but not the names and weights. I want to get sorted everything according to value.
How can i do that?
I've written the following code. But not sure what to do next.
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
class treasure
{
public:
std::string name[100];
double value[100];
double weight[100];
};
int itemNumber, totalWeight, i;
treasure item;
std::cout << "Enter total item weight(in kg): " << std::endl;
std::cin >> totalWeight;
std::cout << std::endl <<"Enter total item number: " << std::endl;
std::cin >> itemNumber;
//take item name, item value, item weight
for( i = 0; i < itemNumber; i++)
{
std::cout << std::endl << "Enter item name: " << "\t" << "Enter item value(per kg): " << "\t" << "Enter item weight(in kg): " << std::endl;
std::cin >> item.name[i] >> item.value[i] >> item.weight[i];
}
//sort items according to given value
std::sort(item.value, item.value + itemNumber);
//print sorted list
for( i = 0; i < itemNumber; i++)
{
std::cout << std::endl << std::endl << "Item name: " << "\t" << "Item value(per kg): " << "\t" << "Item weight(in kg): " << std::endl;
std::cout << item.name[i] << "\t\t" << item.value[i] << "\t\t\t" << item.weight[i] << std::endl;
}
return 0;
}
Your structure should look like this:
class treasure
{
public:
std::string name;
double value;
double weight;
};
and then you declare array of treasures:
treasure item[100];
taking items:
//take item name, item value, item weight
for( i = 0; i < itemNumber; i++)
{
std::cout << std::endl << "Enter item name: " << "\t" << "Enter item value(per kg): " << "\t" << "Enter item weight(in kg): " << std::endl;
std::cin >> item[i].name >> item[i].value >> item[i].weight;
}
and finally sorting:
std::sort(item, item + itemNumber,
[] (auto t1, auto t2) {return t1.value < t2.value;})
http://ideone.com/GL3VKz

How does selection sort work?

This is a selection sort that I'm trying and I don't understand why it isn't working. My understanding is that selection sort scans a vector for the smallest value which when it finds it moves it to the beginning of the vector. It preforms another scan this time ignoring the first element and doing it all over again until n - 1 times where n is the length of the vector.
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <map>
using namespace std;
int main()
{
vector <string> vName, vID, vClass;
string sName, minValue, sID, sClass, sSearch, sQuestion, ssSearch, sSearchN, sSearchI;
int iSize, iStudent;
// Display initial vector size
iSize = vName.size();
cout << "Student list starts with the size:" << iSize << endl;
// Get size of list from user
cout << "How many students would you like to add?" << endl;
cin >> iStudent;
cin.ignore();
// Get names, ids, and classes
for (int i = 0; i < iStudent; i++)
{
cout << "Student" << i + 1 << ":\n";
cout << "Please enter the student name: ";
getline(cin, sName);
vName.push_back(sName);
cout << "Enter ID number ";
getline(cin, sID);
vID.push_back(sID);
cout << "Enter class name ";
getline(cin, sClass);
vClass.push_back(sClass);
}
// Display header
cout << "The list of students has the size of: " << iStudent << endl;
cout << "The Student List" << endl;
cout << "\n";
cout << "Name:" << setw(30) << "ID:" << setw(38) << "Enrolled Class : " << endl;
cout << "--------------------------------------------------------------------------";
cout << "\n";
// for loop for displying list
for (int x = 0; x < vName.size() && vID.size() && vClass.size(); x++)
{
cout << vName[x] << "\t \t \t" << vID[x] << "\t \t \t" << vClass[x] << endl;
}
// Sorting function and for loop to display sorted names
cout << "\n";
cout << "The Student List after Sorting:" << endl;
cout << "\n";
//*************************************
int startScan, minIndex;
for (startScan = 0; startScan < vName.size() - 1; startScan++)
{
minIndex = startScan;
minValue = vName[startScan];
for (int index = startScan + 1; index < vName.size(); index++)
{
if (vName[index] < minValue)
{
minValue = vName[index];
minIndex = index;
}
}
vName[minIndex] = vName[startScan];
vName[startScan] = minValue;
vID[minIndex] = vID[startScan];
vID[startScan] = minValue;
vClass[minIndex] = vClass[startScan];
vClass[startScan] = minValue;
}
//******************
//sort(vName.begin(), vName.end());
//for (int y = 0; y < vName.size(); y++)
//{
// cout << vName[y] << endl;
//}
cout << "\n";
// Search function uses a do while loop that loops so long as the user inputs a "y" or "Y"
do
{
int iPick;
cout << "Search Menu:" << endl;
cout << "1. By Name\n";
cout << "2. By ID\n \n";
cin >> iPick;
if (iPick == 1)
{
cout << "Please Enter a name to be searched:" << endl;
getline(cin >> ws, sSearchN);
if (binary_search(vName.begin(), vName.end(), sSearchN))
{
cout << sSearchN << " was found." << endl << endl;
}
else
{
cout << sSearchN << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << vName[0];
cout << "Please enter Y for Yes and N for No:" << endl << endl;
getline(cin >> ws, sQuestion);
}
else
{
cout << "Please Enter an ID to be searched:" << endl;
getline(cin >> ws, sSearchI);
if (binary_search(vID.begin(), vID.end(), sSearchI))
{
cout << sSearchI << " " << "was found" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
getline(cin >> ws, sQuestion);
}
else
{
cout << sSearchI << " " << "was not found." << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
getline(cin >> ws, sQuestion);
}
}
} while (sQuestion == "Y" || sQuestion == "y");
cout << "Thank you for using this program!" << endl;
return 0;
}
EDIT: posted whole program
So the issue is it doesn't sort at all, just gives back vName unsorted.
Okay upon more further study of the code I think I've figured it out.
So looking at the part of the code that is sorting, the way that it works is actually pretty simple. startScan is an int increments until it becomes equal to the size of the vector in the for loop. In this case it is vName. minIndex will hold the smallest index number which at the time of initialization will be equal to the starScan. Finally minValue is a string (in this case because we have a vector of strings) that acts as a temporary container for the element at vName[scanStart]. In the second for loop index will be incremented through the vector and will test if the element vName[index] is smaller than the temproray container i talked about earlier. If it is than the new temp will be vName[index] after that is done it will exit the inner loop and update and move on to the next smallest value in vName. Understanding this it's easy to make it so that the sorting happens with 2 other vectors. All one has to do is create containers for those vectors like the ones i have here minValueA and minValueB. They will simply be changing as vName changes. That way everything stays in the order in which vName is ordered. I hope that helps someone!
int startScan, minIndex;
string minValue, minValueA, minValueB;
for (startScan = 0; startScan < vName.size() - 1; startScan++)
{
minIndex = startScan;
minValue = vName[startScan];
minValueA = vID[startScan];
minValueB = vClass[startScan];
for (int index = startScan + 1; index < vName.size(); index++)
{
if (vName[index] < minValue)
{
minValue = vName[index];
minValueA = vID[index];
minValueB = vClass[index];
minIndex = index;
}
}
vName[minIndex] = vName[startScan];
vName[startScan] = minValue; //values for vName are being added to the other ones.
vID[minIndex] = vID[startScan];
vID[startScan] = minValueA;
vClass[minIndex] = vClass[startScan];
vClass[startScan] = minValueB;
}
//******************
sort(vName.begin(), vName.end());
for (int y = 0; y < vName.size(); y++)
{
cout << vName[y] << "\t \t \t " << vID[y] << "\t \t \t " << vClass[y] << endl;
}

Creating Table headers?

OK, in this program I am required to make a table based of user input. The problem is I cannot figure out how to get the table headers to properly align with the information that is displayed. The table headers would not line up from lets say if the user enters in Michael for player one and Michael Jordan for player 2. Any advice to allow the headers to properly align with the displayed input regardless of character length would be greatly appreciated, thanks.
Here is my code:
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
using namespace std;
//struct of Basketball Player info
struct BasketballPlayerInfo
{
string name; //player name
int playerNum, //player number
pointsScored; //points scored
};
int main()
{
int index, //loop count
total = 0; //hold total points
const int numPlayers = 5; //nuymber of players
BasketballPlayerInfo players[numPlayers]; //Array of players
//ask user for Basketball Player Info
cout << "Enter the name, number, and points scored for each of the 5 players.\n";
for (index = 0; index < numPlayers; index++)
{
//collect player name
cout << " " << endl;
cout << "Enter the name of player # " << (index + 1);
cout << ": ";
//input validation
if(!(getline(cin, players[index].name)))
{
cout << "Player Name must be alphabetical characters only!\n";
cout << "Program terminating please start over." << endl;
system("pause");
exit(0);
}
//getline(cin, players[index].name);
//collect players number
cout << "Enter the number of player # " << (index + 1);
cout << ": ";
//input validation
if(!(cin >> players[index].playerNum))
{
cout << "Player Name must be numeric characters only!\n";
cout << "Program terminating please start over." << endl;
system("pause");
exit(0);
}
//collect points scored
cout << "Enter points scored for player # " << (index + 1);
cout << ": ";
//input validation
if(!(cin >> players[index].pointsScored))
{
cout << "Player Name must be numeric characters only!\n";
cout << "Program terminating please start over." << endl;
system("pause");
exit(0);
}
cin.ignore();
}
//display
cout << "\n";
cout << "Here is the information for each player: \n";
cout << fixed << showpoint << setprecision(2);
cout << "\n";
cout << " \tName\tNumber\tPoints\n";
cout << "------------------------------------------------" << endl;
for(index = 0; index < numPlayers; index++)
{
cout << "Player # " << (index + 1);
cout << ": \t" << players[index].name << "\t" << players[index].playerNum << "\t" << players[index].pointsScored << endl;
cout << "------------------------------------------------" << endl;
}
//display total points scored by all players
for(index = 0; index < numPlayers; index++)
{
//hold total
total += players[index].pointsScored;
}
cout << "Total Points scored are: " << total << endl;
system("pause");
return 0;
}
you could use setw io manipulator which comes under #include <iomanip>.
cout << setw(20) << "Column1"
<< setw(20) << "Column2"
<< setw(8) << "Column3";
or you could use Boost library
// using Boost.Format
cout << format("%-20s %-20s %-8s\n") % "Column1" % "Column2" % "Column3";
Take a look at the setw and setfill functions. You can use them to assign a minimum width to your columns, which will make for much cleaner output formatting than tabs.