I'm making a list of Student Objects, and want to iterate over them and output the values they have. I'm not sure why the for loop is being skipped over. Any help/guidance would be appreciated. Here is the loop:
void studentInfo(list<Student> stuList) {
cout << "in studentinfo" << endl;
for (list<Student>::iterator it = stuList.begin(); it != stuList.end(); ++it) {
cout << "in student info loop" << endl;
cout << it->toString();
}
cout << "after loop" << endl;
}
I get the cout messages that are right before and after the loop. Here is the toString() method if you need.
string Student::toString() {
stringstream outString;
outString << "Name: " << name << "\nID: " << id << "\nAge: " << age << endl;
return outString.str();
}
This is how the list is being populated, I'm adding 2 student objects usually when testing:
void addToList(list<Student> stuList) {
string tempName;
int tempID;
int tempAge;
int numStudents;
cout << "How many students will you be entering?\n";
cin >> numStudents;
for (int i = 0; i < numStudents; i++) {
cout << "Enter student name: \n";
cin >> tempName;
cout << "Enter student id: \n";
cin >> tempID;
cout << "Enter student age: \n";
cin >> tempAge;
stuList.push_back(Student(tempName, tempID, tempAge));
}
}
Related
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] << " ";
}
}
Alright, so I have an class-inventory assignment for my C++ class. The thing I'm struggling with right now is the part between the loop and object creation.
string description = "";
int id_number{0};
int quantity_number{0};
double price_value{0};
for (int count{1}; count <= inventory_num; count++)
{
cout << endl;
cout << "Item #" << count++ << endl;
cout << "Enter the id number: ";
cin >> id_number;
cout << "Descriptiom: ";
cin.get();
getline(cin, description);
cout << "Quantity on hand: ";
cin >> quantity_number;
cout << "Unit price: ";
cin >> price_value;
cout << endl;
}
InventoryItem item1(id_number, description, quantity_number, price_value);
InventoryItem item2(id_number, description, quantity_number, price_value);
InventoryItem item3(id_number, description, quantity_number, price_value);
InventoryItem item4(id_number, description, quantity_number, price_value);
item1.display(); cout << endl;
item2.display(); cout << endl;
item3.display(); cout << endl;
item4.display(); cout << endl;
return EXIT_SUCCESS;
}
So the problem is, for example, looping the input for 4 times, but the output only shows the the data from the LAST INPUT OF THE LOOP for ALL OF THE OUTPUT(item1,item2,item3,item4). How do fix this lads?
You overwrite the values in each loop iteration. After the loop the values of the last iteration are stored in your variables. You could fix it with a std::vector
#include "InventoryItem.hpp"
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::getline;
int main() {
string description = "";
int id_number{0};
int quantity_number{0};
double price_value{0};
std::vector<InventoryItem> items;
for (int count{1}; count <= inventory_num; count++)
{
cout << endl;
cout << "Item #" << count++ << endl;
cout << "Enter the id number: ";
cin >> id_number;
cout << "Descriptiom: ";
cin.get();
getline(cin, description);
cout << "Quantity on hand: ";
cin >> quantity_number;
cout << "Unit price: ";
cin >> price_value;
cout << endl;
items.emplace_back(id_number, description, quantity_number, price_value);
}
items[0].display(); cout << endl;
items[1].display(); cout << endl;
items[2].display(); cout << endl;
items[3].display(); cout << endl;
return EXIT_SUCCESS;
}
Basically trying to just run this program for extra learning, Xcode won't understand that I have written a class, and wont implement it. Really confused and need some guidance.
When I run the code only the main method is implemented, nothing else works...
#include <iostream>
using namespace std;
class students {
int id;
char name[20];
int s1;
int s2;
int s3;
public:
void getData() {
cout << "Enter the ID " << endl;
cin >> id;
cout << "Enter the name " << endl;
cin >> name;
cout << "Enter the grade in subject 1 " << endl;
cin >> s1;
cout << "Enter the grade in subject 2 " << endl;
cin >> s2;
cout << "Enter the grade in subject 3 " << endl;
cin >> s3;
}
void putData() {
cout << id << " " << name << " " << s1 << " " << s2 << " " << s3 << endl;
}
};
int main () {
students s[20];
int i, n; //i is for the for loop, n for number of students
cout << "Enter the number of students " << endl;
cin >> n;
for (i=0;i>n;i++)
{
s[i].getData();
}
for (i=0;i>n;i++)
{
s[i].putData();
}
return 0;
}
After my first entry, my second entery name field fills up with the input buffer from the previous entry. Why? I am even using the getline but the problem still persists. Please help me with the problem. This is question from Jumping Into C++ book .
#include <iostream>
#include <string>
using namespace std;
struct Person
{
string name;
string address;
long long int PhoneNumber;
};
void displayEntries(Person p[])
{
int enteryNumber;
cout << "Enter the entry number of the person for details(enter 0 to display all entries): ";
cin >> enteryNumber;
if(enteryNumber == 0)
{
for(int i = 0; i < 10; i++)
{
cout << "Entery Number: " << i + 1;
cout << "Name: " << p[i].name << endl;
cout << "Address: " << p[i].address << endl;
cout << "Phone Number: " << p[i].PhoneNumber << endl;
}
}
do
{
cout << "Entery Number: " << enteryNumber;
cout << "Name: " << p[enteryNumber].name << endl;
cout << "Address: " << p[enteryNumber].address << endl;
cout << "Phone Number: " << p[enteryNumber].PhoneNumber << endl;
} while (enteryNumber != 0);
}
int main()
{
Person p[10];
for(int i = 0; i < 10; i++)
{
cout << "Enter the details of the person\n\n";
cout << "Name: ";
getline(cin, p[i].name);
cout << "Address: ";
getline(cin, p[i].address);
cout << "Phone Number: ";
cin >> p[i].PhoneNumber;
cout << endl;
}
displayEntries(p);
return 0;
}
You can see what is happening when you read the reference for getline:
When used immediately after whitespace-delimited input, e.g. after
int n;
std::cin >> n;
getline(cin, n); //if used here
getline consumes the endline character left on the input stream by operator>>, and returns immediately. A common solution is to ignore all leftover characters on the line of input with
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
before switching to line-oriented input.
cin >> p[i].PhoneNumber; only gets the number. That leaves the line ending still in the input buffer to be read the next time you try to read a line.
i'm trying to load the file into an array when the program starts so i can
modify or search in it i don't know if my code works or not ( it's not reading the file )i have the file
and there's two books in
i have tried to debug it but couldn't find the problem the code works
but it think there's a problem with the load() function i don't know what
my code :
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
struct books{
//identfying books with all needed things
int id, status;
string title, p_name, p_address;
string date;
string aut_name, aut_nationality;
}newbook[10000], aut[10000];
int i = 0;
void load(){
ifstream myfile("books.txt", ios::in);
while (myfile >> newbook[i].id >> newbook[i].title >> newbook[i].p_name >> newbook[i].p_address >> aut[i].aut_name >> aut[i].aut_nationality >> newbook[i].date >> newbook[i].status)
i++;
}
void search_for_book(){
int temp = 0;
int idx;
cout << "enter the ID of the book you're looking for : ";
cin >> idx;
for (int srh = 0; srh < i; srh++){
if (newbook[srh].id == idx){
cout << setw(10) << "book found :" << endl;
cout << "title :" << newbook[srh].title << endl;
cout << "publisher name : " << newbook[srh].p_name << endl;
cout << "publisher address" << newbook[srh].p_address << endl;
cout << "author name :" << aut[srh].aut_name << endl;
cout << "author Nationality :" << aut[srh].aut_nationality << endl;
cout << "publish Date :" << newbook[srh].date << endl;
cout << "status :" << newbook[srh].status << endl;
temp++;
break;
}
else
srh++;
}
if (temp == 0){
cout << "couldn't find book" << endl << endl;
}
}
int main(){
load();
char choice;
cout << "enter your choice (3)";
cin >> choice;
if (choice == '3'){
search_for_book();
}
}
note :*( there are other functions like adding new book but not necessary to write )
*(i'm new to c++ don't really know how to read file into memory but i'm trying)
this is the code to save data into file :
void add_new_book_5(){
int booksnumber;
books newbook[1000], aut[100];
cout << "how many books you want to add ? ";
cin >> booksnumber;
cout << "what books you want to add :" << endl;
d_base.open(path, ios::out | ios::app);
for (int i = 0; i < booksnumber; i++){
cout << "id please : "; cin >> newbook[i].id;
cout << "title : "; cin.ignore(); getline(cin, newbook[i].title);
cout << "publisher name :"; getline(cin, newbook[i].p_name);
cout << "publisher address : "; getline(cin, newbook[i].p_address);
cout << "author" << " name : "; cin.ignore(); getline(cin, newbook[i].aut_name);
cout << "Nationality : "; getline(cin, newbook[i].aut_nationality);
cout << "Publish date :"; getline(cin, newbook[i].date);
cout << "How many copies of " << newbook[i].title << " "; cin >> newbook[i].status;
system("cls");
d_base << newbook[i].id << "\ " << newbook[i].title << "\ ";
d_base << newbook[i].p_name << "\ " << newbook[i].p_address << "\ ";
d_base << newbook[i].aut_name << "\ " << newbook[i].aut_nationality << "\ ";
d_base << newbook[i].date << "\ " << newbook[i].status << endl;
}
d_base.close();
cout << setw(76) << "Books Have Been Saved Sucessfully" << endl;
}