Can I put a string, int, and double in a vector? - c++

In my program, I'm having an issue with one function trying to put three different types into an array. Is that possible, or do I have to work around this? I need them in one vector so I can recall that array in another function to delete it.
void addStudent()
{
string major;
double gpa;
unsigned seed = time(0);
srand(seed);
int rand_ID = rand() % 9000 + 1000;
cout << "Please enter major" << endl;
cin >> major;
cout << "Please enter GPA" << endl;
cin >> gpa;
cout << "------Add Student------" << endl;
cout << "ID: " << rand_ID << endl;
cout << "Major: " << major << endl;
cout << "GPA: " << gpa << endl;
ofstream students;
students.open("students.txt", ios_base::app);
students << rand_ID << " " << major << " " << gpa << endl; // I want to turn this into an array that I can send to the file students
}

It sounds like you want to put different students in a vector; and those students will be represented by a struct containing an int ID, string major and double GPA.
struct Student {
int id;
std::string major;
double gpa;
};
std::vector<Student> students;

Related

Multiplying string by a const int C++

#include <iostream>
#include <string>
using namespace std;
int main() {
//declaring cin inputs
string userName;
string userMiles;
string userSteps;
//declaring constant for number of steps/mile
const int stepsPerMile = 2000;
//getting user's name
cout << "What is the user's name?";
cin >> userName;
cout << endl;
//getting miles walked
cout << "How many miles did " << userName << " hike today?";
cin >> userMiles;
cout << endl;
//getting other steps taken
cout << "How many other steps did " << userName << " take today?";
cin >> userSteps;
cout << endl;
string stepsTakenFromMiles;
string totalSteps;
stepsTakenFromMiles = userMiles * stepsPerMile;
totalSteps = stepsTakenFromMiles + userSteps;
cout << userName << " took " << totalSteps << " steps throughout the day." << endl;
return 0;
}
I am trying to multiply userMiles (string) by stepsPerMile (const int) and I keep getting an error that they are not matching operand types. I have to use stepsPerMile as a const int and cannot change it. How do I change my code to allow both of these inputs to be multiplied?
Read in userMiles and userSteps as integers, not as strings. operator>> can read in many different types, not just std::string. Try using int instead, to match your stepsPerMile constant, eg:
#include <iostream>
#include <string>
using namespace std;
int main() {
//declaring cin inputs
string userName;
int userMiles;
int userSteps;
//declaring constant for number of steps/mile
const int stepsPerMile = 2000;
//getting user's name
cout << "What is the user's name?";
cin >> userName;
cout << endl;
//getting miles walked
cout << "How many miles did " << userName << " hike today?";
cin >> userMiles;
cout << endl;
//getting other steps taken
cout << "How many other steps did " << userName << " take today?";
cin >> userSteps;
cout << endl;
int stepsTakenFromMiles;
int totalSteps;
stepsTakenFromMiles = userMiles * stepsPerMile;
totalSteps = stepsTakenFromMiles + userSteps;
cout << userName << " took " << totalSteps << " steps throughout the day." << endl;
return 0;
}
Demo
a nice program I checked it out. Cool program, I like it. I think to solve this problem. Instead of making userMiles a string, make it an int like this
#include <iostream>
#include <string>
using namespace std;
int main() {
//declaring cin inputs
string userName;
int userMiles;
string userSteps;
//declaring constant for number of steps/mile
const int stepsPerMile = 2000;
//getting user's name
cout << "What is the user's name?";
cin >> userName;
cout << endl;
//getting miles walked
cout << "How many miles did " << userName << " hike today?";
cin >> userMiles;
cout << endl;
//getting other steps taken
cout << "How many other steps did " << userName << " take today?";
cin >> userSteps;
cout << endl;
string stepsTakenFromMiles;
string totalSteps;
stepsTakenFromMiles = userMiles * stepsPerMile;
totalSteps = stepsTakenFromMiles + userSteps;
cout << userName << " took " << totalSteps << " steps throughout the day." << endl;
return 0;
}
Just change your identifiers
int userMiles, userMiles;
because in C++ you can't use the multiplication operator with strings, this can be actually used in other programming languages such as python like when you multiply a string by a number the string will be repeated but in C++ you can't use arithmetic operators with string except "+" which can be used to join 2 or more strings.
This is a c++ course for beginners check it hope it helps

How to create a function to read/write data to struct members?

I'm trying to create a program that read and print students' data with c++. for that, I've created a struct Student, a function to read data from the user and assign it to a struct instance s1 and a function to print students' data on the screen, and I think the problem is with the function that read/write data.
Here is the my code:
#include<iostream>
#include<string>
using namespace std;
struct Student
{
char name[30];
int age;
double gpa;
string department;
};
Student read_data(Student x)
{
cout << "Name (30 characters maximum): ";
cin.get(x.name, 30);
cout << "Age: ";
cin >> x.age;
cout << "Department: ";
cin >> x.department;
cout << "GPA: ";
cin >> x.gpa;
return x;
}
void print_data(Student x)
{
cout <<
"\n***************************************************************" << endl;
cout << "Name: " << x.name << endl;
cout << "Age: " << x.age << endl;
cout << "Department: " << x.department << endl;
cout << "GPA: " << x.gpa << endl;
}
int main()
{
Student s1, s2, s3;
cout << "This program stores -Temporarily- data of three students\n" << endl;
cout << "Enter 1st student's data" << endl;
read_data(s1);
print_data(read_data(s1));
system("pause");
return 0;
}
The output of this code is:
This program stores data of three students
Enter 1st student's data
Name (30 characters maximum): Ahmed Maysara
Age: 22
Department: CS
GPA: 3.5
Name (30 characters maximum): Age: Department: GPA:
***************************************************************
Name:
Age: -858993460
Department:
GPA: -9.25596e+61
Press any key to continue . . .
As you see, the output is out of my expectations :) ..
Any help ?!
Both CinCout and David are correct.
There are a couple of problems with your code as it now stands.
The first problem is that while you successfully call the function read_data(s1), s1 is a just a copy. So, when the function sets all of the values for the student using cin, it is really just setting a copy's values. You can either make it so that you are passing in the original, or you can return the student (which you are doing) and set s1 equal to the result (which you are not).
To make sure that you pass in the original, you can go to where you declared read_data. Instead of saying Student read_data(Student x), you should place an ampersand after the parameter that you don't want to copy Student read_data(Student &x). This is called passing by reference (you reference the original instead of referencing by copy)
Alternatively, you could con just set s1 to the result where you call it in main. You could say s1 = read_data(s1); and that would work fine, though a bit more inefficiently.
Lastly, the other glaring error in the code is that you accidentally call read_data again when you say print_data(read_data(s1)). Instead, say print_data(s1).
Instead of passing and returning the structure object each time on call of read_data and print_data we could add those inside the structure itself, We could create object of Student and call the functions read and print within the same.
struct Student
{
char name[30];
int age;
double gpa;
string department;
Student(): age(0), gpa(0)
{
memset( name, 0, 30 );
}
void read()
{
cout << "\nName (30 characters maximum): ";
cin.get(name, 30);
cout << "\nAge: ";
cin >> age;
cout << "\nDepartment: ";
cin >> department;
cout << "\nGPA: ";
cin >> gpa;
}
void print()
{
cout << "\n***************************************************************" << endl;
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Department: " << department << endl;
cout << "GPA: " << gpa << endl;
}
};
int main()
{
Student s1;
s1.read();
s1.print();
return 0;
}
You are passing copy of s1 into the read_data function, but not bothering to update the value based on the return arg. i.e. something like this should work.
s1 = read_data(s1);
print_data(s1);
Alternatively, pass by reference instead of value:
void read_data(Student& x)
{
cout << "Name (29 characters maximum): "; // requires null terminator
cin >> x.name; // just read into the buffer directly
cout << "Age: ";
cin >> x.age;
cout << "Department: ";
cin >> x.department;
cout << "GPA: ";
cin >> x.gpa;
}
And then later:
read_data(s1);
print_data(s1);
change you read_data with something like this
void read_data(Student& x)
{
cout << "Name (30 characters maximum): ";
///cin.get(x.name, 30);
cin.getline(x.name, 30);
cout << "Age: ";
cin >> x.age;
cin.ignore();
cout << "Department: ";
std::getline(cin, x.department);
///cin >> x.department;
cout << "GPA: ";
cin >> x.gpa;
cin.ignore();
// return x; can't return a value from a void function
}
and in main function or where you are calling the read_data function use
Student s1, s2, s3;
cout << "This program stores -Temporarily- data of three students\n" << endl;
cout << "Enter 1st student's data" << endl;
read_data(s1);
read_data(s2);
read_data(s3);
the reason you are getting weird values in return is that you capture buffer with cin >> instead getline
see
description of getline function
description of cin.ignore function

Why won't Xcode (10.1) realize this class? What am I doing wrong

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

Using a struct to hold information entered by the user C++

Okay, so I am writing a C++ program to declare a struct data type that holds the following information on an employee (First Name, Last Name, ID, Pay Rate, and Hours). My problem is that the user can only enter in the ID and First Name, then the whole program runs without letting the user enter the rest of the data.
Heres my code:
#include <iostream>
#include <iomanip>
using namespace std;
struct Employee
{
int employeeID;
char firstName;
char lastName;
float payRate;
int hours;
};
int main()
{
int i, j;
cout << "How Many Employees Do You Wish To Enter?:\n\n";
cin >> j;
Employee info;
for (i = 0; i < j; i++)
{
cout << "Enter in the Data for Employee number " << i + 1 << endl;
cout << setw(5) << "\n Please Enter The Employee ID Number: ";
cin >> info.employeeID;
cout << setw(5) << "\n Please Enter Employees First Name: ";
cin >> info.firstName;
cout << setw(5) << "\n Please Enter Employees Last Name: ";
cin >> info.lastName;
cout << setw(5) << "\n Please Enter Employees Pay Rate: ";
cin >> info.payRate;
cout << setw(5) << "\n Please Enter The Hours The Employee Worked:
";
cin >> info.hours;
}
cout << "\n\n \n";
cout << "ID" << setw(15) << "First Name" << setw(10) << "Last Name" <<
setw(10) << "Pay Rate" << setw(10) << "Hours";
cout << endl;
for (i = 0; i < j; i++)
{
cout << "\n" << info.employeeID << setw(15) << info.firstName << setw(10) << info.lastName << setw(10) << info.payRate << setw(10) << info.hours;
}
cout << "\n\n \n";
system("pause");
return 0;
};
#include <iostream>
#include <iomanip>
#include <string> //Allows you to use strings, which are way more handy for text manipulation
#include <vector> //Allows you to use vector which are meant to be rezied dynamicaly, which is your case
using namespace std;
struct Employee
{
int employeeID;
string firstName; //HERE : use string instead of char (string are array of char)
string lastName; //HERE : use string instead of char
float payRate;
int hours;
};
int main()
{
int j;
cout << "How Many Employees Do You Wish To Enter?:\n\n";
cin >> j;
vector<struct Employee> info; //creation of the vector (dynamic array) to store the employee info the user is going to give you
for (int i = 0; i < j; i++) //declare your looping iterator "i" here, you will avoid many error
{
struct Employee employee_i; // create an employee at each iteration to associate the current info
cout << "Enter in the Data for Employee number " << i + 1 << endl;
cout << "\n Please Enter The Employee ID Number: ";
cin >> employee_i.employeeID;
cout << "\n Please Enter Employees First Name: ";
cin >> employee_i.firstName;
cout << "\n Please Enter Employees Last Name: ";
cin >> employee_i.lastName;
cout << "\n Please Enter Employees Pay Rate: ";
cin >> employee_i.payRate;
cout << "\n Please Enter The Hours The Employee Worked: ";
cin >> employee_i.hours;
info.push_back(employee_i); //store that employee info into your vector. Push_back() methods expands the vector size by 1 each time, to be able to put your item in it
} // because you employee variable was create IN the loop, he will be destruct here, but not the vector which was created outside
cout << "\n\n \n";
for (int i = 0; i < j; i++) //the loop to get back all the info from the vector
{
cout << "ID :" << info[i].employeeID << " First Name :" << info[i].firstName << " Last Name :" <<
info[i].lastName << " Pay Rate :" << info[i].payRate << " Hours :"<< info[i].hours;
cout << endl;
//notice the info[i], which leads you to the employee you need and the ".hours" which leads to the hours info of that specific employee
}
system("pause");
return 0;
}
First, please read Tips and tricks for using C++ I/O (input/output). It might be helpful to understand C++ I/O.
Here are some comments on your code:
First
Use string instead of char.
struct Employee
{
int employeeID;
string firstName;
string lastName;
float payRate;
int hours;
};
Second
Use array of Employee object to store multiple employees.
Employee info[100];
Third
Use cin carefully depending data types. In your case, it would be something like this:
cout << "Enter in the Data for Employee number " << i + 1 << endl;
cout << setw(5) << "\n Please Enter The Employee ID Number: ";
cin >> info[i].employeeID;
cin.ignore(); //It is placed to ignore new line character.
cout << setw(5) << "\n Please Enter Employees First Name: ";
getline (cin, info[i].firstName);
cout << setw(5) << "\n Please Enter Employees Last Name: ";
getline (cin, info[i].lastName);
cout << setw(5) << "\n Please Enter Employees Pay Rate: ";
cin >> info[i].payRate;
cout << setw(5) << "\n Please Enter The Hours The Employee Worked: ";
cin >> info[i].hours;
Fourth
std::getline() can run into problems when used before std::cin >> var. So, std::cin.ignore() can be used in this case to solve the problem.
I hope it helps.

Error: ld returned 1 exit status June 2015

I need help understanding the [Error] id return 1 exit status due to 2 undefined references: getGrades() and getAverage(). I was issued DEV C++ and knocked out the syntax errors with mild frustration but these "linking" errors are still giving me a hard time. This is the most recent update of the code, if anyone could help me understand these linking errors that would be great.
Compiler - Dev C++
Windows 7
Code:
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
// Function declarations
string getStudentName();
string getWork();
int getGrades();
double getAverage();
int main()
{
string studentName, work[3];
int grades[3];
double average;
// Get the name of the student
studentName = getStudentName();
// Get the work
work[3] = getWork();
// Get the grades
grades[3] = getGrades();
// Get the average
average = getAverage();
// Dynamic spacing for grades
ostringstream ss;
int gradesLength = ss.str().length();
ss <<setprecision(0) << fixed << showpoint;
ss << grades;
cout << "\n the average for " << studentName << " is: " << average << endl;
cout << "The grades for " << studentName << " are: " << endl;
cout << setw(30) << work[0] << ": " << setw(gradesLength) << grades[0] << endl;
cout << setw(30) << work[1] << ": " << setw(gradesLength) << grades[1] << endl;
cout << setw(30) << work[2] << ": " << setw(gradesLength) << grades[2] << "\n\n\n";
cout << "You have completed the program: \n";
return 0;
}
// Student Name
string getStudentName()
{
string name;
cout << "Enter students full name: ";
getline(cin, name);
return name;
}
// Assignments
string getWork()
{
string work[3];
cout << "\nEnter the name of each assignment \n";
cout << "First assignment: ";
getline (cin, work[0]);
cout << "Second assignment: ";
getline (cin, work[1]);
cout << "Third assignment: ";
getline (cin, work[2]);
return work[3];
}
// Grades
int getGrades(string work[3])
{
int grades[3];
cout << "\nEnter the grade for " << work[0] << ": ";
cin >> grades[0];
cout << "Enter the grade for " << work[1] << ": ";
cin >> grades[1];
cout << "Enter the grade for " << work[2] << ": ";
cin >> grades[2];
return grades[3];
}
// Math
double getAverage(int grades[3])
{
double average;
average = (grades[0] + grades[1] + grades[2]) / 3.0f;
return average;
}