Trying to enter data for each string initializer - c++

My first question here, though I've lurked for a while. Very new to programming, sorry for bad formatting in this post, my brain is fried. I like to do the homework completely on my own, but I'm completely snagged at this point.
We are to retrieve and process data in a scenario where five different types of salsa are being sold. I know how to display the string of salsa types, I know how to process it once the user enters the correct number of jars sold.
I'm stuck on trying to get the user input number of jars sold to appear after each salsa type is listed.
ex: Enter the number of jars sold according to salsa type
Mild: (User enters data here)
Medium: (User enters data here)
etc.
I can only seem to get user input data to appear after the names are listed:
Enter the number of jars sold according to salsa type
Mild:
Medium:
etc.
(User enters data here)
Heres what I have so far:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
// variables
const int SIZE = 5;
string salsas[SIZE] = { "Mild", "Medium", "Sweet", "Hot", "Zesty"};
//names of salsas
int jars; //holds number of jars user enters
cout << "Here are the salsa types:\n";
// Display the salsas in the array
for (int count = 0; count < SIZE; count++)
cout << salsas[count] << ": " << endl;
cin >> jars[salsas];
return 0;
}
Any help is appreciated!

#include <iostream>
#include <string>
using namespace std;
int main(){
// variables
const int SIZE = 5;
string salsas[SIZE] = { "Mild", "Medium", "Sweet", "Hot", "Zesty"};
//names of salsas
int jars[SIZE]={0}; //holds number of jars user enters
cout << "Here are the salsa types:\n";
// Display the salsas in the array
for (int count = 0; count < SIZE; count++) {
cout << salsas[count] << " : ";
cin >> jars[count];
}
return 0;
}

Related

What is wrong with the for loop that is trying to get input from user?

What is wrong with the for loop that is getting cname and camount from the user.
Here is my input:
size = 3
Name = "Asha R"
It throws me out of the loop and exits the program. I should be able to enter 3 names and 3 amounts based on the size I entered in the first statement.
I've tried to change the cin statements several different ways, but nothing is working. Your help is much appreciated:
#include <iostream>
#include <string>
using namespace std;
struct contribution {
string cname;
double camount = 0.0;
};
int main ()
{
int size = 0;
//get array size from user
cout << "How many members do you want to enter" << endl;
cin >> size;
//create dynamic array of contribution structure
contribution * conarr = new contribution[size];
//This is my problem area. When I enter the 1st loop and enter "Asha R" it kicks out of the loop. I tried to change the cin statements several different ways, but it's not working.
for (int i=0; i < size; i++)
{
cout << "Enter name: " ;
//getline(cin, conarr[i].cname);
getline(cin,conarr[i].cname).get();
cout << "Enter contribution amount: ";
// cin >> conarr[i].camount;
(cin >> conarr[i].camount).get();
}
delete[] conarr;
}

C++: Program crashes when I try to access a private class string variable. Why is this, and what can I do to fix it?

I am writing a bank account program that provides a menu system for the user, which allows them to choose between 4 options: A) Add a customer, B) Print all customer data, C) Update customer data, and D) Exit program. Each option performs separate tasks. The option I am focused on for this question is Option A.
Option A is supposed to generate a new bank account object and ask the user to input the account holder name, the initial deposit for the account (how much money to start with for the new account), and the interest rate. It then needs to set these values to the correct private values in the bankAccount class for any given object.
Code for main.cpp before Option B (there is a little more code after this, hence the lack of backward brackets at the end, but I want to try and keep this more concise):
#include <iostream>
#include <string>
#include <cstdlib>
#include "header.h"
#include "implementation.cpp"
using namespace std;
int main()
{
//array of bankAccount class objects (up to 20)
bankAccount account[20];
string menuInput = ""; //used for menu loop input
string accNameInput = ""; //used for account customer name user input
float depositInput = 0; //used for initial deposit input
float interestInput = 0; //used for initial interest input
// int customerCount = 0; //used to compare to static int to determine # of customers in memory
int static i = 0;
//while loop keeps user in the menu until they choose to exit program
while (true)
{
cout << endl << "Enter a letter option below: "
<< endl << endl << "A: Add a customer" << endl << "B: Print all customer data available"
<< endl << "C: Update customer data" << endl << "D: End program" << endl << endl;
cin >> menuInput;
//Option A: Add a customer
if (menuInput == "A" || menuInput == "a")
{
//checking for max customer limit
if (i > 19)
{
cout << endl << "Cannot add customer; Max customer capacity reached." << endl;
}
else //
{
///Creates a new customer account and asks for new customer name,
///initial deposit amount, & interest
cout << endl << "Bank account #" << (i + 1) << " created." << endl;
bankAccount account[i]; //new bank account object created
//time to set the name for our new customer...
cout << endl << "Enter customer name for account #" << (i + 1) << ": " << endl;
cin >> accNameInput;
//setting initial deposit amount
cout << endl << "Enter initial deposit amount for account #" << (i + 1) << ": " << endl;
cin >> depositInput;
//setting initial interest rate
cout << endl << "Enter interest rate (without % sign): " << endl;
cin >> interestInput;
account[i].setInterestRate(interestInput);
account[i].setBalance(depositInput);
account[i].setAccountHolderName(accNameInput);
//increments the account number counter
i++;
}
}
The problem persists with setAccountHolderName() found on the last line here:
account[i].setInterestRate(interestInput);
account[i].setBalance(depositInput);
account[i].setAccountHolderName(accNameInput);
When I call the class functions setInterestRate and setBalance to set the input values to their respective private class variables, the program proceeds like normal and takes the user back to the main menu as it should. But calling setAccountHolderName crashes the program and returns this value: -1073741819 (0xC0000005).
I'll include some code from the header and implementation files below to show how I have accountHolderName code programmed in:
header.h (includes accountHolderName get/set functions):
///Name of file: header.h
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <iostream>
#include <string>
using namespace std;
class bankAccount
{
//private data values
string accountHolderName;
int accountNumber;
//static int accCounter; //keeps track of account numbers
float balance;
float interestRate;
public:
//Default constructor
bankAccount();
///Getters/setters for all private member variables
//accountNumber
int getAccountNumber();
void setAccountNumber(int accNum);
//accountHolderName
string getAccountHolderName();
void setAccountHolderName(string accName);
implementation.cpp (includes accountHolderName implementation):
///Name of file: implementation.cpp
#include <iostream>
#include <string>
#include "header.h"
using namespace std;
//static int definition (guess you have to define static members here?)
//int bankAccount::accCounter;
//Default constructor
bankAccount::bankAccount()
{
accountHolderName = "";
accountNumber = 0;
// accCounter = 0;
balance = 0;
interestRate = 0;
}
///Getters/setters for all private member variables
//accountNumber
int bankAccount::getAccountNumber()
{
return accountNumber;
}
void bankAccount::setAccountNumber(int accNum)
{
accountNumber = accNum;
}
//accountHolderName
string bankAccount::getAccountHolderName()
{
return accountHolderName;
}
void bankAccount::setAccountHolderName(string accName)
{
accountHolderName = accName;
}
It seems like messing with the code in certain ways (such as completely deleting the code that comes after Option A's code, commenting out accountHolderName = ""; in the default constructor, etc.) will temporarily allow account[i].setAccountHolderName(accNameInput); to function without crashing the program, but this is incredibly inconsistent and confuses me even more. I'm not sure if the issue has to do with memory or what. I have also tried using cout to see if the input variable accNameInput from main.cpp is getting stored to, which it is.
Sorry if this is simply too much code or explaining; this is my first post and I just wanted to provide a good chunk of my code so you could see the full scale of things. All I am trying to do here is access the bankAccount class private string variable, accountHolderName, and store user input into each new object.
I tried troubleshooting this issue online but couldn't seem to find anything that had a similar issue. I'm not sure what I'm missing; any help or guidance would be incredibly appreciated.
Technically, this line:
bankAccount account[i]; //new bank account object created
Isn't allowed in C++, but some compilers (g++) allow it as an extension since they do formally support variable stack arrays with the C compiler.
Further, that declaration overrides the variable of the same name declared at a higher scope
But then you get to these lines:
account[i].setInterestRate(interestInput);
account[i].setBalance(depositInput);
account[i].setAccountHolderName(accNameInput);
But valid indices of an array range for 0..i-1 So you're already in undefined behavior with your array index out of bounds.
I suspect you really meant this:
bankAccount newAccount; //new bank account object created
...
newAccount.setInterestRate(interestInput);
newAccount.setBalance(depositInput);
newAccount.setAccountHolderName(accNameInput);
account[i] = newAccount;
i++;

How do I make my program pass data to my array correctly? (Homework)

I've set my array size to 20 (I set it to 19 assuming it's counting 0). I set my for loop to only run so long as gradeCount <= to gradeCounted yet it will keep running no matter how many times I enter data. If I enter 3 grades without pressing enter between each one, such as "23 23 23" it will return "Enter Grade" 3 times in a row, rather, for as many grades as I enter, separated by spaces. I don't understand why it's not passing data into the array and ending the for loop properly. I'm sure my code is an ugly mess, sorry.
Also, when entering code into stackoverflow, it said to indent the code 4 spaces to format? I couldn't initially indent the code with the code button and there was no {} button either. What am I missing? It was only after a notification to fix it that I was able to. Thanks for your time, I don't want to be a pain in the ass for you guys.
//This program asks user how many grades there are, inputs grades, and displays median of said grades.
#include <iostream>
using namespace std;
//Variables
////////////////////const int limitGrades = 20; //Array "boxes"? //Ignore this //for now.
int gradeCounted; //Number of grades from user.
const int SIZE = 19;
//Array
float grades[19]; //Max grades that can be entered.
//Functions
void gradeTaker()
{
cout << "You may input up to 20 grades. \n";
cout << "First enter the number of grades you have: \n";
cin >> gradeCounted;
//requests how many grades there are and stores them in array
for (int gradeCount = 0; gradeCount <= gradeCounted + 1; gradeCount++)
{
for (float &grade : grades)
{
cout << "Enter grade: \n";
cin >> grade;
}
}
};
int main()
{
gradeTaker();
cout << "grades so far";
for (int grade : grades)
cout << grade << endl;
system("pause");
}
The size of the array is separate from how you access it. Accessing 20 values is the equivalent to accessing indices from 0 to 19.
float grades[20];
for(size_t i = 0; i < 20; i++){ // print all values of grades
std::cout << grades[i] << "\n";
}
Furthermore, your for loop in gradeTaker will ask you for a value for each index of grades a total of gradeCounted + 2 times. To fix this, only iterate over the indices that you're assigning a value to like so:
for (int gradeCount = 0; gradeCount < gradeCounted; gradeCount++){
cout << "Enter grade: \n";
cin >> grade[gradeCount];
}
Finally... the for loop in your main function will iterate across the entire array which may include uninitialized values. You should initialize the array or use a dynamic data structure like std::vector and just push_back the necessary values.
(P.s. highlight code in the text-block and press CTRL+K to indent.)

Why is my c++ program terminating with no output in Eclipse but works in Visual Studio? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
My program was running in visual studio on Windows, but when I tried working on it in Eclipse on Ubuntu, it would terminate when I tried to run, without showing any output at all.
Eclipse is using the Linux GCC toolkit.
I have no compiler errors or warnings or anything, the console just shows the bit saying it terminated and then blank.
I went into debugging and came up with
Shop [1188] [cores: 1]
Thread [1] 1188 [core: 1] (Suspended : Signal : SIGSEGV:Segmentation fault)
0x7ffff7b78bca
std::string::assign() at 0x7ffff7b79ff6
operator=() at basic_string.h:542 0x402f00
fillInventory() at shop.cpp:364 0x402f00
main() at shop.cpp:73 0x401a29
I think that it's not opening the input file, but I'm not sure ... main and prototypes are below:
input file :ball_inventory.txt
output file :ball_reportData.txt
*/
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
using namespace std;
//CLASSES and STRUCTURES
struct inventory
{
string name; //name of item
int cost; //cost of item
int stock; //items in stock
int deficit; //items ordered but not provided when out of stock
};
//PROTOTYPES
//Receive and validate input for yes/no prompts.
char yesNo();
//Display shop's logo
void logo();
//Display the low level item menu
void lowLevelMenu(int limit, inventory lowLevelInv[]);
//perform a purchase action for a single individual
int purchase(int limit, inventory lowLevelInv[], int itemTally[]);
//populate the inventory array with name, price, stock, data, initialize deficit to 0.
int fillInventory(ifstream &fin, inventory lowLevelInv[]);
//sort the inventory array by the day's deficit
void sortByDeficit(inventory lowLevelInv[], int limit);
//BODY
/*
* Function Procedure:
* 1. Prompt "customer 1" user for purchases
* 3. Update group total
* 3. Loop until there are no more "customers"
* 4. Output group total
* 5. If no more groups, prompt for password.
* 6. At end of day, output to file, 1 line per item: name, stock, deficit.
*/
int main()
{
const int INV = 20; //sets size of item[] and parallel arrays
char confirm = 'n'; //holds user response to y/n prompts
int groupTot; //Group's total cost
ifstream invSrc; //inventory resource file
ofstream ball_reportData; //output file for report
int limit; //number of populated elements in arrays
string password = "98765"; //sets manager password
string passCheck; //user input to be checked against password
bool exitAllow = 0; //allows program to generate report and exit
int itemTally[INV]; //tally of items ordered by a user
inventory lowLevelInv[INV]; //contains inventory information for the low level inventory
invSrc.open("ball_inventory.txt"); //open inventory file, populate arrays, close inventory file.
/*LINE 73*/ limit = fillInventory(invSrc, lowLevelInv);
invSrc.close();
logo(); //display shop logo
while(!exitAllow) //continue running until password is entered to set exitAllow to true
{
groupTot = 0; //initialize group total due to 0;
groupTot += purchase(limit, lowLevelInv, itemTally); //prompt first customer for purchases and update group total
do
{
cout<<"Are there any more orders for this group? y/n: "; //check for more customers
confirm = yesNo();
if(confirm == 'y') //prompt additional users and update total for each
{
groupTot += purchase(limit, lowLevelInv, itemTally);
}
}while(confirm == 'y');
cout<<"The group's total is: "<<groupTot<<" denarii."; //output total for group
cout<<"\n\nAre you done for the day?"; //confirm for more groups to calculate
confirm = yesNo();
while(confirm == 'y')
{
cout<<"Enter your password:";
cin>>passCheck;
if(password != passCheck)
{
cout<<"Invalid password, try again? ";
confirm = yesNo();
}
else
{
exitAllow = 1;
confirm = 'n';
}
}
}
for(int i = 0; i<limit; i++)
{
cout << lowLevelInv[i].stock << endl;
}
for(int i = 0; i<limit; i++)
{
cout << lowLevelInv[i].deficit << endl;
}
cout << string(20, '-')<<endl;
sortByDeficit(lowLevelInv, limit);
ball_reportData.open("ball_reportData.txt");
for(int i = 0; i<limit; i++)
{
ball_reportData << lowLevelInv[i].name << endl;
ball_reportData << lowLevelInv[i].stock << endl;
ball_reportData << lowLevelInv[i].deficit << endl;
}
cout<<"\n\nPress Enter to finish...";
cin.ignore();
cin.get();
return(0);
}
Fill Inventory:
int fillInventory(ifstream &fin, inventory lowLevelInv[])
{
string name = "junk"; //name to be input to itemArray
string cost;
string stock; //cost to be input to costArray
int i = 0; //incrementer
stringstream convert; //string stream used to input string to int
int max=0; //Number of elements filled in array
while(name != "none") //until "none" in file, fill name/cost arrays
{
getline(fin, name); //get name line
getline(fin, cost); //get cost line
getline(fin, stock);
if(name != "none")
{
/*LINE 364*/ lowLevelInv[i].name = name; //output to name array
convert<<cost; //fill stringstream
convert >> lowLevelInv[i].cost; //output stringstream to cost array
convert.clear(); //clear EOF(?) flag
convert<<stock; //fill stringstream
convert >> lowLevelInv[i].stock; //output stringstream to cost array
convert.clear(); //clear EOF(?) flag
lowLevelInv[i].deficit = 0; //set initial deficit
max++;
}
i++;
}
return max;
}
As guys at "No Console Output (MinGW, CDT)" point out, this is probably (or at least sometimes) because Eclipse does not add PATH to MINGW\bin when launching the executable, so:
In the "Environment" tag, press "New", set it as:
"Name:PATH"
"Value:C:\MinGW\bin"

How to input values after for loop in C++?

I have to make a program which inputs 10 student's grades and displays their weighed and unweighted averages. I am new to C++ programming so I don't know much and my professor doesn't like it when people use things he hasn't taught.
Here's the code: It shows up as What are the four test scores of student 1,2, etc. How can I make it to be when it says "What are the four test scores of student 1", then I would be able to enter those in. And then on to student2, student3, etc?
Thank you for your time.
#include <iostream>
using namespace std;
const int numberofstudents = 10;
int main()
{
int student;
for(student=1; student<=numberofstudents; student++)
cout << "\nWhat are the four test scores of student number " << student << endl;
return 0;
}
I think you want to read four values for each students, if so , then understand this code:
#include <iostream>
using namespace std;
int main()
{
const int numberofstudents = 10;
double scores[numberofstudents][4];
for(int student=0; student<numberofstudents; student++)
{
cout << "\nWhat are the four test scores of student number " << (student+1) << endl;
int i = 0;
while ( i < 4 )
{
//scores is a two dimentional array
//scores first index is student number (starting with 0)
//and second index is ith score
cin >> scores[student][i]; //read score, one at a time!
i++;
}
}
//process scores...
}
Now since it's your homework, do the rest of your work yourself. All the best!