Getting data from every for loop - c++

I want to output every data that I entered in the for loop in a tabular form. Unfortunately, the output only displays the last set of data that I entered. Any solution to solve this?
#include <iostream>
using namespace std;
int main()
{
double voltage, rpm, current, range;
int total; // total set enter by user
cout << "Please enter how many sets of data you want to calculate:";
cin >> total;
cout << "\n";
for(int i=1; i<=total; i++)
{
cout << "Enter he voltage " << i << ":";
cin >> voltage;
cout << "Enter the current " << i << ":";
cin >> current;
cout << "Enter the rpm " << i << ":";
cin >> rpm;
cout << endl;
double range = (voltage*1.2) + (current*0.5) + (rpm* 0.2);
}
cout << "Voltage\t\tCurrent\t\tRPM\t\tRange\n";
for(int i=1; i<=total; i++)
{
cout << voltage << "\t\t" << current << "\t\t" << rpm
<< "\t\t" << range << endl;
}
return 0;
}

This variables
double voltage,rpm,current,range;
each can only store a single double. To store many doubles, use a std::vector<double>:
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
int main()
{
std::vector<double> voltages;
int total; //total set enter by user
cout << "Please enter how many sets of data you want to calculate:";
cin >> total;
cout << "\n";
for(int i = 1; i <= total; i++)
{
double voltage;
cout << "Enter he voltage " << i << ":";
if (cin >> voltage) {
voltages.push_back(voltage);
} else {
cout << "invalid input. Try again \n";
}
}
cout << "Voltage\n";
for (const auto& volt : voltages) {
cout << volt << "\n";
}
}
Instead of using many vectors you should use a data structure:
struct my_data {
double voltage;
double rpm;
double current;
double range;
}
And use a std::vector<my_data>.
Once you have that you should take a look at how to overload the input operator << for that data structure. But one thing at a time ;).
PS Don't use spaces so sparingly. Readability of code cannot be overestimated. And take a look at Why is “using namespace std;” considered bad practice?. Sooner or later it will create you problems.

You can create a vector of tuple to store the required data.
#include <iostream>
#include <vector>
#include <tuple>
using namespace std;
int main()
{ double voltage,rpm,current,range;
int total; //total set enter by user
cout << "Please enter how many sets of data you want to calculate:";
cin>>total;
cout<<"\n";
std::vector<std::tuple<double, double, double, double>> data;
for(int i=1;i<=total;i++)
{
cout<<"Enter he voltage "<<i<<":";
cin>>voltage;
cout<<"Enter the current "<<i<<":";
cin>>current;
cout<<"Enter the rpm "<<i<<":";
cin>>rpm;
cout<<endl;
double range= (voltage*1.2) + (current*0.5) + (rpm* 0.2);
data.emplace_back(std::make_tuple(current, current, rpm, range));
}
cout<<"Voltage\t\tCurrent\t\tRPM\t\tRange\n";
for(const auto& tup : data)
cout<<std::get<0>(tup)<<"\t\t"<<std::get<1>(tup)<<"\t\t"<<std::get<2>(tup)<<"\t\t"<<std::get<3>(tup)<<endl;
return 0;
}

Related

How to add getline in c++?

I am looking to remove the space from the name part of my assignment which allows users to put any name with or without space in my product list. for example "TV stand", I assume getline function will help me with it but I couldn't add the getline function into my main. can anyone help me with it?
#include <bits/stdc++.h>
#include <iostream>
#include <string>
using namespace std;
struct product {
char product_name;
int no_of_purchase;
int no_of_sales;
double purchase_cost;
double selling_price;
double profit_loss;
double percent_profit_loss;
string product_sales;
};
bool Compare(product P1, product P2)
{
return P1.percent_profit_loss > P2.percent_profit_loss;
}
int main()
{
int n;
cout << "Enter the number of the product:";
cin >> n;
cout << "\n";
product Products[n];
for (int i = 0; i < n; ++i) {
cout << "Enter the name of the product: ";
cin >> Products[i].product_name;
cout << "Enter the number of " << Products[i].product_name << " purchased: ";
cin >> Products[i].no_of_purchase;
cout << "Enter the number of " << Products[i].product_name << " sold: ";
cin >> Products[i].no_of_sales;
To be honest I don't understand your question but this might be helpful for you
I changed the product_name data type from char to string because the char data type is not making any sense
#include <iostream>
#include <string>
using namespace std;
struct product {
string product_name;
int no_of_purchase;
int no_of_sales;
double purchase_cost;
double selling_price;
double profit_loss;
double percent_profit_loss;
string product_sales;
};
bool Compare(product P1, product P2)
{
return P1.percent_profit_loss > P2.percent_profit_loss;
}
int main()
{
int n;
cout << "Enter the number of the product:";
cin >> n;
cin.ignore();
cout << "\n";
product Products[n];
for (int i = 0; i < n; ++i) {
cout << "Enter the name of the product: ";
getline(cin, Products[i].product_name);
cout << "Enter the number of " << Products[i].product_name << " purchased: ";
cin >> Products[i].no_of_purchase;
cout << "Enter the number of " << Products[i].product_name << " sold: ";
getline(cin, Products[i].no_of_sales);
cin.ignore();
}
return 0;
}

Can a loop be used to collect multiple vairables?

I want to promt for a string variable (name of item) and then promt for a double variable (cost). I want this to be done 5 times so each time it loops the vales are stored as a different pair of variable.
need to have user input an item and then its price so i can calc a bill.
not sure if I can crate a loop for this or i need to keep a running count somehow
int main()
{
int i;
string Item_1,Item_2,Item_3,Item_4,Item_5;
double Price_1,Price_2,Price_3,Price_4,Price_5 ;
while (i<6)
{
cout<<"Please enter item"<<endl;
cin>> Item_1>>Item_2>>Item_3>>Item_4>>Item_5>>endl;
cout<<"Please enter cost of " >> Item_1>>Item_2>>Item_3>>Item_4>>Item_5;
cin>>Price_1>>Price_2>>Price_3>>Price_4>>Price_5;
i=i++
}
return 0;
}
Code doesn't compile but i expect it to ask for my in put for the 5 variables 5 times
Here is a solution with arrays and a for loop.
You can try it in CPP Shell.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string Item[5];
double Price[5] ;
for(int i = 0; i < 5; i++)
{
cout<<"Please enter item"<<endl;
cin>> Item[i];
cout<<"Please enter cost of " << Item[i] << ":" << endl;
cin>>Price[i];
}
cout << "Items: ";
for(int i = 0; i < 5; i++)
{
cout << Item[i] << " ";
}
cout << endl << "Prices: ";
for(int i = 0; i < 5; i++)
{
cout << Price[i] << " ";
}
return 0;
}
Your code doesn't compile for many reasons!
Of course you can use a loop for your purpose. Consider the following code, which is not really good, but does the job:
#include <string>
#include <iostream>
using namespace std;
int main()
{
int i = 1;
string Item[5];
double Price[5];
while (i<6)
{
cout<<"Please enter item "<< i << ": ";
cin>>Item[i-1];
cout<<endl;
cout <<"Please enter cost of "<< Item[i-1] << ": ";
cin >> Price[i-1];
i++;
};
i = 1;
while (i<6)
{
cout << "Item " << i << ": " << Item[i-1] << ", Price: " << Price[i-1] << endl;
i++;
};
return 0;
}

Opening a file and outputting for function

I have a code that I am doing and I got the basic version to work, I need help with how to implement a function in which the program reads a text file that I have saved and reads it and outputs it based on the function. Here is my code and what I have so far..
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
//start main
int main()
{
double cost_merchandise, salary, yearly_rent, electricity_cost;
double totalCost, netProfit;
double PERCENTAGE_SALE = 0.15;
double PERCENTAGE_GOAL = 0.10;
double after_sale;
double Mark_up;
string line;
ifstream myfile ("F:/Intro To C++/ch0309.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
//gets data
cout << "Enter merchandise cost: ";
cin >> cost_merchandise;
cout << "Enter employee salary: ";
cin >> salary;
cout << "Enter yearly rent: ";
cin >> yearly_rent;
cout << "Enter the estimated electricity cost: ";
cin >> electricity_cost;
totalCost = cost_merchandise + salary + yearly_rent + electricity_cost;
//Output expenses, calculate mark ups, cost after 15%
cout << endl << setprecision(2) << fixed;
cout << "\nThe Company's expenses equals $: " << totalCost << endl << endl;
netProfit = cost_merchandise * PERCENTAGE_GOAL;
after_sale = netProfit + totalCost;
Mark_up = (after_sale - cost_merchandise) / 100;
cout << "A 10% profit is valued at $: " << netProfit << endl;
cout << "Mark Up is " << Mark_up * 100 << "%" << endl;
return 0;
}
//end of main
Here is a way to do it, assuming that your data is splited by whitespaced or new lines :
#include <string>
#include <vector>
#include <fstream>
template<typename T>
std::vector<T> getDataFromFile(const std::string& filename) {
std::ifstream file_input_stream(filename);
if (!file_input_stream)
throw std::exception("ifstream failed to open");
std::vector<T> data;
T input_data;
while (!(file_input_stream >> input_data).eof()) {
data.push_back(input_data);
}
return data;
}
and you use it like this :
auto int_vector = getDataFromFile<int>(filename);
// You can modify the template parameter with the good data type ( char, double, string... )
//To output the vector :
for (const auto& i : int_vector) {
std::cout << i;
}

organizing array from least to greatest c++

Hi I'm working on a project that lets the user input numbers and the code organizes them in order of least to greatest and tells how many of each number was input. I'm having problems with the organizing of least to greatest and counting how many of each number are inputed
using namespace std;
#include <iostream>
void main(){
double a[30];
double e[30];
double b;
int c[30];
int d;
double f=0;
cout << "how many input values [max 30]:";
cin >> d;
cout << "enter " << d << " numbers:"<<endl;
for(int x=0; x<d;x++){
cin >> a[x];
c[x]=0;
}
cout << endl;
for(int y=0; y<d;y++){
if(a[y]>=f){
f=a[y];
}
}
for(int z=0;z<d;z++){
if(a[z]){
c[z]++;
}
if(a[z]>=a[z+1]){
e[z]=a[z];
}
}
cout << "numbers count"<< endl;
for(int printloop=0;printloop<d;printloop++){
if(a[printloop]>0){
cout << e[printloop]<< " " << c[printloop] << endl;
}
}
cout << "max value:" << b << endl;
}
Solution base on std::map http://en.cppreference.com/w/cpp/container/map, note the Compare template argument and C++11 (http://en.cppreference.com/w/cpp/language/range-for)
#include <iostream>
#include <map>
int main(int argc, char** argv)
{
std::map<int, int> count;
int n;
std::cout << "How many numbers ? ";
std::cin >> n;
std::cout << "Now enter " << n << " numbers : ";
for(auto i=0; i<n; i++)
{
int tmp;
std::cin >> tmp;
count[tmp]++;
}
for(auto const& elem : count )
std::cout << "Element " << elem.first << " count : " << elem.second << "\n";
return 0;
}

Sort names alphabetically

I'm trying to sort names alphabetically
e.g If user enters names and GPA:
Names GPA
Peter 2.8
Robert 5.6
David 7.8
The output should be : -
Names GPA
David 7.8
Peter 2.8
Robert 5.6
Here is my program so far (INCOMPLETE):-
#include <iostream>
using namespace std;
int main()
{
char name [5][25];
float gpa [5];
int i;
for (i=0 ; i<5 ; i++)
{
cout << "Enter name " << i+1 << " : ";
cin >> name [i];
cout << "Enter GPA : ";
cin >> gpa [i];
cout << endl;
}
cout << "\n********** Your entered data **********\n\n";
cout << "\tName" << "\t\t" << "GPA\n\n";
for (i=0 ; i<5 ; i++)
{
cout << "\t" << name [i] << "\t\t" << gpa [i];
cout << endl;
}
for (i=0 ; i<5 ; i++)
{
for (int j=0 ; j<1 ; j++)
{
cout << (int) name [i][j] << endl;
}
}
cout << "\n\n******* Sorted data (w.r.t name) *******\n\n";
cout << "\tName" << "\t\t" << "GPA\n\n";
for (i=0 ; i<5 ; i++)
{
cout << "\t" << name [i] << "\t\t" << gpa [i];
cout << endl;
}
cout << endl;
return 0;
}
Remember, only name should be sorted alphabetically. I have taken the ASCII values of the first characters of entered names in the middle for loop but:-
1- ASCII code for 's' is not the same as 'S' (That's a problem for me)
2- I can't seem create a logic to compare the ASCII values of the first letters of names then sort them accordingly. Then afterwards linking the name with the sorted letter list and displaying the result. Also the GPA should be linked with the names.
Any help would be appreciated.
Here's an answer using std::sort. I changed some of your C-like approach and using std::sort actually forces me to do it. The comparison function(compareStudents) needs objects so I had to create the struct. Vector has been used for the same reason although it would have been possible to keep using arrays but that's generally frowned upon.
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
struct Student {
string name;
float gpa;
Student(string name, float gpa) {
this->name = name;
this->gpa = gpa;
}
};
bool compareStudents(Student a, Student b) {
return a.name.compare(b.name) < 0;
}
int main() {
const int studentCount = 2;
vector<Student> studentVector;
int i;
for (i = 0 ; i < studentCount ; i++) {
cout << "Enter name " << i + 1 << " : ";
string name;
cin >> name;
cout << "Enter GPA : ";
float gpa;
cin >> gpa;
cout << endl;
studentVector.push_back(Student(name, gpa));
}
cout << "\n********** Your entered data **********\n\n";
cout << "\tName" << "\t\t" << "GPA\n\n";
vector<Student>::iterator it = studentVector.begin();
for (; it != studentVector.end(); ++it) {
Student student = *it;
cout << "\t" << student.name << "\t\t" << student.gpa;
cout << endl;
}
sort(studentVector.begin(), studentVector.end(), compareStudents);
cout << "\n\n******* Sorted data (w.r.t name) *******\n\n";
cout << "\tName" << "\t\t" << "GPA\n\n";
it = studentVector.begin();
for (; it != studentVector.end(); ++it) {
Student student = *it;
cout << "\t" << student.name << "\t\t" << student.gpa;
cout << endl;
}
cout << endl;
return 0;
}
If you convert the names' character to upper-case using std::toupper you should then just be able to compare the the strings using < operator.
Edit: if you don't want to use std::sort :-)
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
class stu
{
char name[40];
int cgpa;
public:
void assign()
{cin>>name;
cin>>cgpa;
}
void display()
{cout<<name<<endl<<cgpa<<endl;
}
friend void align(stu *s,int v);
};
void align(stu *s,int v)
{for(int j=0;j<v-1;j++)
{for(int i=0;i<v-j-1;i++)
{//buble sort
if(strcmp((s+i)->name,(s+i+1)->name)>0)
{char l[40];
strcpy(l,(s+i)->name);
strcpy((s+i)->name,(s+i+1)->name);
strcpy((s+i+1)->name,l);
//swapping cgpa
int t=(s+i)->cgpa;
(s+i)->cgpa=(s+i+1)->cgpa;
(s+i+1)->cgpa=t;
}
}}}
int main()
{stu s[10];int i;
for(i=0;i<5;i++)
s[i].assign();
align(s,5);
cout<<endl<<endl;
for(i=0;i<5;i++)
s[i].display();
}
#include <string>
#include <algorithm>
using namespace std;
int main()
{
//zbuduj program wyswietlajacy w kolejnosci alfabetycznej 5 wczytanych imion
string wyrazy[5];
int c;
for(int i=0; i<5;i++){
c= i +1;
cout<<"podaj imie "<<c<<"; ";
cin>>wyrazy[i];
}
sort(wyrazy, wyrazy+5);
cout<<"posortowane"<<endl;
for(int b=0; b<5;b++){
cout<<wyrazy[b]<<endl;
}
return 0;
}