Can a loop be used to collect multiple vairables? - c++

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

Related

Output does not include all input for my array

I have this program that is barely started:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <string>
using namespace std;
class Grade
{
public:
string studentID;
int userChoice = 0;
int size = 0;
double* grades = new double[size]{0};
};
void ProgramGreeting(Grade &student);
void ProgramMenu(Grade& student);
string GetID(Grade& student);
int GetChoice(Grade& student);
void GetScores(Grade& student);
int main()
{
Grade student;
ProgramGreeting(student);
ProgramMenu(student);
}
// Specification C1 - Program Greeting function
void ProgramGreeting(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << "Welcome to the GPA Analyzer! " << endl;
cout << "By: Kate Rainey " << endl;
cout << "Assignment Due Date: September 25th, 2022 " << endl;
cout << "--------------------------------------------" << endl;
GetID(student);
cout << "For Student ID # " << student.studentID << endl;
}
void ProgramMenu(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << setw(25) << "Main Menu" << endl;
cout << "1. Add Grade " << endl;
cout << "2. Display All Grades " << endl;
cout << "3. Process All Grades " << endl;
cout << "4. Quit Program." << endl;
cout << "--------------------------------------------" << endl;
GetChoice(student);
}
string GetID(Grade &student)
{
cout << "Enter the student's ID: ";
cin >> student.studentID;
if (student.studentID.length() != 8) {
cout << "Student ID's contain 8 characters ";
GetID(student);
}
return student.studentID;
}
int GetChoice(Grade &student)
{
cout << "Enter your selection: ";
cin >> student.userChoice;
if (student.userChoice == 1) {
GetScores(student);
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 4)
{
exit(0);
}
else
{
cout << "Please enter 1, 2, 3 or 4" << endl;
GetChoice(student);
}
}
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
for (int i = 0; i < student.size; i++) {
student.grades[i] = score;
}
count++;
}
for (int i = 0; i < student.size; i++) {
cout << student.grades[i] << " ";
}
}
I am trying to make sure my array is recording all test scores, but when I output the array in my GetScore function, each element in the array is the same or equal to the last score I entered. For example, if I choose 3 for size and then enter three values of 99.2 86.4 90.1, all three elements will read 90.1.
Why is this happening?
Your Grade class is allocating an array of 0 double elements (which is undefined behavior), and then your GetScores() function does not reallocate that array after asking the user how many scores they will enter, so you are writing the input values to invalid memory (which is also undefined behavior).
Even if you were managing the array's memory correctly (ie, by using std::vector instead of new[]), GetScores() is also running a for loop that writes the user's latest input value into every element of the array, instead of just writing it to the next available element. That is why your final output displays only the last value entered in every element. You need to get rid of that for loop completely.
Try something more like this instead (there are several other problems with your code, but I'll leave those as separate exercises for you to figure out):
class Grade
{
public:
...
int size = 0;
double* grades = nullptr;
};
...
void GetScores(Grade &student)
{
int size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
if (student.size != size) {
delete[] student.grades;
student.grades = new double[size]{0};
student.size = size;
}
for(int i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
for (int i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
Alternatively:
#include <vector>
...
class Grade
{
public:
...
vector<double> grades;
};
...
void GetScores(Grade &student)
{
size_t size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
student.grades.resize(size);
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
/* alternatively:
student.grades.clear();
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades.push_back(score);
}
*/
for (size_t i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
I removed my for loop from my while loop.
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
student.grades[count] = score;
count++;
}
for (int j = 0; j < student.size; j++) {
cout << student.grades[j] << " ";
}
}

The part of my code where a search for a name in a string isnt working.(it always says it doesnt exist) Any ideas

In int menu() i have 2 options how to add ships
#include <iostream>
using namespace std;
Ship input() { //to input info for 1 ship
Ship S = { 0 };
cout << "\n Enter ship number:"; cin >> S.number;
cin.ignore();
cout << "\n Enter the name of the ship:"; cin.getline(S.name, 50);
cout << "\n Enter the load capacity of the ship:"; cin >> S.capacity;
return (S);
}
int enter(Ship Lib[], int n) { //to input infor for multiple ships
int i, m;
do {
cout << "\n Enter information for how many ships(max 5 in one go):";
cin >> m;
} while (m < 0 || m>5);
if (n + m < 20) { // max number of ships i can have is 20
for (i = n; i < n + m; i++) {
cout << "\n Ship " << i + 1;
Lib[i] = input();
}
return (n + m);
}
else cout << "\n You can't add any more ships!";
}
void Ship_by_Name(Ship Lib[], int n) { //search for a ship by its name
char Sname[50];
cin.ignore();
cout << "\n Ship name: ";
cin.getline(Sname, 50);
for (int i = 0; i < n; i++)
if (!strcmp(Sname, Lib[i].name)) {
cout << "\n Ship found!";
cout << "\n Number: " << Lib[i].number << "\t Name: " << Lib[i].name << "\t Load capacity: "
<< Lib[i].capacity;
break; //how i break the loop when i find what i need
}
else cout << "\n This ship isn't recorded!"; //this line prints 3 times?
}
But i think void Ship_by_Name has no access to Ship input now that im looking at it.
So i think i need to make it available to Ship_by_name somehow

Trying to break out of a string loop

Okay so I've been troubleshooting an issue I have with my "process" function below. When I submit my code, I get the correct output but my loop never ends. When I try to end the loop, I get no output. I know how to end the loop if the variable is an integer but the string is throwing me for a loop. I'm new to this, and I'm sure the solution is probably right in front of my face. Thanks for the help.
int process()
{
double price = 0;
while(true)
{
int items = 0;
string order = "";
cout << "Enter your order string: ";
cin >> order;
items = findItem(order);
if (items < 0)
{
cout << order << " is invalid. Skipping it.\n";
break;
}
cout << names[items] << ": $" << fixed << setprecision(2) << prices[items] << endl;
price += prices[items];
}
cout << "Total: $" << fixed << setprecision(2) << price;
}
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;
const int MAXPRODUCTS = 100;
string names[MAXPRODUCTS];
double prices[MAXPRODUCTS];
string codes[MAXPRODUCTS];
int numProducts = 0;
void readConfiguration()
{
int i =0;
ifstream finput("menu.txt");
while(finput >> codes[i] >> names[i] >> prices[i])
{
i++;
numProducts = i;
}
}
//return valid index if the item is found, return -1 otherwise.
int findItem(string inputCode)
{
for(int i =0; i<numProducts; i++)
{
if(inputCode == codes[i])
return i;
}
return -1;
}
// read order string like "A1 A1 E1 E2 S1" and generate the restaurant bill.
// Output the item name and price in each line, total in the final line.
int process()
{
string order = "";
while(true)
{
int items = 0;
cout << "Enter your order string: ";
cin >> order;
items = findItem(order);
if (items < 0)
{
cout << order << " is invalid. Skipping it.\n";
continue;
}
else
cout << names[items] << ": $" << fixed << setprecision(2) << prices[items] << endl;
}
return 0;
}
int main()
{
readConfiguration();
process();
}
try to edit while(true) to while(cin >> order)
while(cin >> order)
{
int items = 0;
cout << "Enter your order string: ";
items = findItem(order);
if (items < 0)
{
cout << order << " is invalid. Skipping it.\n";
continue;
}
else
cout << names[items] << ": $" << fixed << setprecision(2) << prices[items] << endl;
}

If statement to control range of numbers using array

I have created an array that holds 5 numbers, and the user inputs the numbers. If the mark is less than 0 and greater than 100, I want to print out "invalid mark number". How could I do that?
using namespace std;
int mark[5];
int main ()
{
cout << "enter mark 0: ";
cin >> mark[0];
cout << "enter mark 1: ";
cin >> mark[1];
cout << "enter mark 2: ";
cin >> mark[2];
cout << "enter mark 3: ";
cin >> mark[3];
cout << "enter mark 4: ";
cin >> mark[4];
}
You should use a for-loop to make the code more readable and compact. Because once you introduce if statements, the code size would grow alot. It should look like this:
#include <iostream>
using namespace std;
int mark[5];
int main () {
for (int i = 0; i < 5; i++){
cout << "enter mark " << i << ": ";
cin >> mark[i];
if (mark[i] < 0 || mark[i] > 100){
cout << "invalid mark number\n";
}
}
}
Don't use using namespace std; (read here why) and keep the int mark[5]; inside the main-function (read here why). Also to add to the logic force the user to input again:
#include <iostream>
int main () {
int mark[5];
for (int i = 0; i < 5; i++){
bool valid_input = false;
while (!valid_input){
std::cout << "enter mark " << i << ": ";
std::cin >> mark[i];
if (mark[i] < 0 || mark[i] > 100){
std::cout << "invalid mark number\n";
}
else{
valid_input = true;
}
}
}
}

how to call functions and unused expression error

I get an error saying: use of undeclared identifier 'again'.
I am trying to go from int main to void again and back after getting an answer.
Please explain to me why it won't work also. Thanks.
Here is my full code:
#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
{
string answer;
cout << "Would you like to enter another set of data? Y or N?" << endl;
cin << answer;
string yes = "Yes";
string no = "No";
if(a == yes)
{
main();
}
}
int main()
{
cout << "Kaitlin Stevers" << endl;
cout << "Exercise 11 - Vectors" << endl;
cout << "November 12, 2016" <<endl;
cout << endl;
cout << endl;
int size;
cout << " How many numbers would you like the vector to hold? " << endl;
cin >> size;
vector<int> numbers;
int bnumbers;
for (int count = 0; count < size; count++)
{
cout << "Enter a number: " << endl;
cin >> bnumbers;
numbers.push_back(bnumbers); // Adds an element to numbers
}
//display the numbers stored in order
cout << "The numbers in order are: " << endl;
for(int bcount = 0; bcount < size; bcount++)
{
cout << numbers[bcount] << " ";
}
cout << endl;
//display the numbers stored reversed
cout << "Here are the numbers in reverse order: " << endl;
reverse(numbers.begin(), numbers.end());
for(int rcount = 0; rcount < size; rcount++)
{
cout << numbers[rcount] << " ";
}
cout << endl;
again();
return 0;
}
void again()
}
You need to declare your fonction "again" before calling it :
#include <iostream>
#include <vector>
#include <iomanip>
#include <algorithm>
#include <string>
using namespace std;
void again();
int main()
{
cout << "Kaitlin Stevers" << endl;
cout << "Exercise 11 - Vectors" << endl;
cout << "November 12, 2016" <<endl;
cout << endl;
cout << endl;
int size;
cout << " How many numbers would you like the vector to hold? " << endl;
cin >> size;
vector<int> numbers;
int bnumbers;
for (int count = 0; count < size; count++)
{
cout << "Enter a number: " << endl;
cin >> bnumbers;
numbers.push_back(bnumbers); // Adds an element to numbers
}
//display the numbers stored in order
cout << "The numbers in order are: " << endl;
for(int bcount = 0; bcount < size; bcount++)
{
cout << numbers[bcount] << " ";
}
cout << endl;
//display the numbers stored reversed
cout << "Here are the numbers in reverse order: " << endl;
reverse(numbers.begin(), numbers.end());
for(int rcount = 0; rcount < size; rcount++)
{
cout << numbers[rcount] << " ";
}
cout << endl;
again();
return 0;
}
void again()
{
string answer;
cout << "Would you like to enter another set of data? Y or N?" << endl;
cin >> answer;
string yes = "Yes";
string no = "No";
if(answer == yes)
{
main();
}
}
However, it's a strange things to use recursivity for what you want to do and to call main func multiple times (which is by definition, main entry of a program). In my opinion, you should call in your main function another function named like askInformation which uses a loop with a test case to know if user wants to add informations or not.