I need help in structure in c++ - c++

The program is to take a structure with object name "st" will take age and then first and last name than standard
But it is saying this error
(main.cpp:33:10: error: invalid use of non-static member function ‘void Student::age(int)’)
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct Student{
static string f,l;
static int a,s;
void age(int ag);
void first_name(string fi)
{
f=fi;
}
void last_name(string la)
{
l=la;
}
void standard(int st)
{
s=st;
}
};
void Student :: age( int ag)
{
a=ag;
}
int main() {
Student st;
cin >> st.age >> st.first_name >> st.last_name >> st.standard;
cout << st.age << " " << st.first_name << " " << st.last_name << " " << st.standard;
return 0;
}

Right now it's really unclear what you're trying to achieve with your code.
First of all, your problem is because trying to to put some input into member functions that take arguments, you need to get your input into temporary arguments and pass them, you should also rename your member function to set_age, set_first_name, etc. to indicate what they're doing.
Student st;
int age;
std::string first_name;
std::string last_name;
int standard;
std::cin >> age >> first_name >> last_name >> standard;
st.set_age(age);
st.set_first_name(first_name);
st.set_last_name(last_name);
st.set_standard(standard);
Then you're trying to output them using the same functions without calling them again, but even if you did, they return void, so nothing. You need a different set of member functions to access those variables.
class Student{
int age;
/* rest of the code */
int get_age() const {
return age;
}
};
int main() {
Student student;
student.set_age(10);
std::cout << student.get_age() << '\n';
}
It also looks like you don't know what static means inside a class, right now all your instances of Student class will share age, first_name, last_name and standard, which is probably not what you ment.

Related

I want to use a variable set in function in main program but errors in declaring variable

I have declared and set a variable in a separate .cpp file but not the main file. I want the value given in the function to be used in the main program. I have included below the main file, function file and header file.
main.cpp:
#include <iostream>
#include "create_character.h"
int main() {
set_gender();
set_age();
std::cout << "Your character is a " << age << " year old "
<< gender << "." << std::endl;
}
character.cpp:
#include <iostream>
#include "create_character.h"
std::string set_gender()
{
std::string gender;
std::cout << "Would you like your character to be male or female? Type m for male or f for female.";
std::cin >> gender;
if (gender == "m")
{
gender = "male";
}
if (gender == "f")
{
gender = "female";
}
}
int set_age() {
int age;
std::cout << "How old is your character?";
std::cin >> age;
}
character.h:
#include <string>
std::string set_gender();
int set_age();
Your functions are non-void functions, thus they have to return some value. You have a function std::string set_gender() in which you create a variable gender, you set this variable but never return it from the function. The same applies to your int set_age() function:
int set_age() {
int age;
std::cout << "How old is your character?";
std::cin >> age;
return age;
}
std::string set_gender()
{
std::string gender;
std::cout << "Would you like your character to be male or female? Type m for male or f for female.";
std::cin >> gender;
if (gender == "m")
{
gender = "male";
}
if (gender == "f")
{
gender = "female";
}
return gender;
}
Furthermore, when you call these functions, you have to assign their return values to a variable so you can use the returned values later:
int main() {
const std::string gender = set_gender();
const int age = set_age();
std::cout << "Your character is a " << age << " year old "
<< gender << "." << std::endl;
}
Note, that when you declare a variable, you can only use the variable in the scope where this variable is declared. The scope is given by the {} brackets. So when you create a variable age in your int set_age() function, you can only use this variable in this int set_age() function, not outside the function. You can, however, copy the value somewhere else, to another variable - that's what return age; does. Then you can assign this returned value to a new variable in your int main() where you can use this variable in the scope of the int main() function.
Also, on a side note - you should use some include guards in your header file so that you'd ensure that the file would only be included once in the translation unit (cpp file). You can either use #pragma once statement at the beginning of the header file, or you can do it using preprocessor macros, which is more portable:
character.h:
#ifndef PATH_TO_CHARACTER_H_ // include guard
#define PATH_TO_CHARACTER_H_
#include <string>
std::string set_gender();
int set_age();
#endif // PATH_TO_CHARACTER_H_ // end of include guard

Some doubts regarding linter in c++

My ide is showing linter error in the following code. It is highliting yellow in the int main() student s; part
using namespace std;
class student {
public:
int age,DOB;
char name[32];
void getData() {
cin >> age >> DOB >> name;
}
void display() {
cout << name << ends << age << ends << DOB ;
}
};
int main() {
student s;
s.getData();
s.display();
}
and the following code which is same but on adding curlys after student s in the int main student part solves the problem
using namespace std;
class student {
public:
int age,DOB;
char name[32];
void getData() {
cin >> age >> DOB >> name;
}
void display() {
cout << name << ends << age << ends << DOB ;
}
};
int main() {
student s{};
s.getData();
s.display();
}
Your IDE most likely points out that the member variables of s are not initialized.
Using {} syntax ensures that it is initialized.
You can read more about typed of initialization in C++ here.
Your IDE is most likely working with C++ 11.
This method is called as extended initializer lists
This syntax is not required in modern compilers
Try upgrading your IDE to Code blocks 17.12 for C++ codes its very handy!!!

How to let a user add to and remove from "slots" in an array?

I have a project in my C++ class - we're supposed to make a "simple student management system" comprised of a class for the student attribute variables, and a main function with a branch statement that lets the user input names and IDs for the students. I know that I need to use an array to make "slots" for the students, and that my branch statements need to let the user input values into those slots, but I'm not exactly sure how to do it. Here is the code that I have so far.
#include <string>
#include <iostream>
#include <utility>
using std::string;
using std::cin;
using std::cout;
using std::endl;
struct Student {
private:
int id;
string name;
int birthday;
public:
Student()
{
id = 0;
birthday = 0;
}
Student(int id, string name, int birthday)
{
//set your parameters to the class variables
this->id = id;
this->name = name;
this->birthday = birthday;
}
void setID(int id)
{
this->id = id;
}
int getID() {
return id;
}
void setName(string name)
{
this->name = name;
}
string getName()
{
return name;
}
void setBirthday(int birthday)
{
this->birthday = birthday;
}
int getBirthday()
{
return birthday;
}
void output() {
cout << id << name << birthday << endl;
}
};
int main() {
Student arr[50];
cout << "Student Management System" << endl;
cout << "Press 'a' to add a student" << endl;
char a = 1;
int y = 1;
while (a == 'a') {
switch (y)
{
cout << "Input Student ID:";
cin >> id;
}
}
}
What I'm focusing on most is the fourth line from the bottom. I was told that I need to use my setters, so I said that I want what my user inputs to be treated as the value of the ID variable that I set in the class. However, when I wrote this out, I was given an error. Could someone tell me what the issue is?
You should try to get your switch statement working correctly. To use classes setters, you can store the user input to a temporary variable then from your one student you can call the member function. i.e. in your case:
arr[index].setID(tempInputVariable);
There is no id in your main function or as a global variable.
I suggest you overload operator >> to have your structure extract its members from the data stream:
struct Student
{
//...
public:
friend std::istream& operator>>(std::istream& input, Student& s);
};
std::istream& operator>>(std::istream& input, Student& s)
{
input >> s.id;
input >> s.name;
input >> s.birthday;
return input;
}
Although the above code doesn't use setters, it is the preferred method for inputting data.
The overload can be modified to use setters (kind of overkill):
std::istream& operator>>(std::istream& input, Student& s)
{
int id;
input >> id;
s.setID(id);
std::string name;
input >> name;
s.setName(name);
int birthday;
input >> birthday;
s.setBirthday(birthday);
return input;
}
If you don't like the overload, you can perform the steps in your main function:
//...
Student new_student;
//...
{
int student_id;
std::cout << "Input Student ID:";
std::cin >> student_id;
new_student.setID(student_id);
std::string student_name;
std::cout << "Input Student Name: ";
std::cin >> student_name;
new_student.setName(student_name);
int student_birthday;
std::cout << "Input Student Birthday: ";
std::cin >> student_birthday;
new_student.setBirthday(student_birthday);
}
Edit 1: The Database
You'll probably need to store or remember the students. This is easy using the first method above:
std::vector<Student> database;
Student s;
std::cout << "Enter student information (ID, Name and birthday, separated by spaces:\n";
std::cin >> s;
// Append to the database
database.push_back(s);
If you haven't learned std::vector you can try an array:
const size_t MAXIMUM_STUDENTS = 16;
Student database[MAXIMUM_STUDENTS];
size_t database_index = 0;
//...
Student s;
std::cout << "Enter student information (ID, Name and birthday, separated by spaces:\n";
std::cin >> s;
// Append to database
database[database_index] = s;
++database_index;

using code blocks for c++ I'm trying to print out an accessor function from my class. the error states that request for member get_address

This is my code it includes the main, header and source file I'm trying to print out an accessor function from my class AddressSpace, but its saying that
request for member "get_address" in "ob", which is of non-class type AddressSpace(std::string, std::string, std::string, int) {aka AddressSpace(std::basic_string, std::basic_string, std::basic_string, int)}
main.cpp
#include <iostream>
#include <string>
#include "AddressSpace.h"
#include "AddressSpace.cpp"
using namespace std;
int main()
{
string address;
string town;
string state;
int postal;
cout << "What is the street you live on?: " <<endl;
cin >> address;
cout << "What is the city you live in?: " <<endl;
cin >> town;
cout <<"What is the state you live in?: " << endl;
cin >> state;
cout << "What is the postal code?: " << endl;
cin >> postal;
AddressSpace ob(string address,string town,string state,int postal);
cout << "Address" << ob.get_address() << endl;
return 0;
}
AddressSpace.h
#ifndef ADDRESSSPACE_H_INCLUDED
#define ADDRESSSPACE_H_INCLUDED
#include <iostream>
#include <string>
using namespace std;
class AddressSpace{
public:
//Default constructor
AddressSpace();
//overload constructor
AddressSpace(string, string, string, int);
//Accessor Functions
string get_address() const;
// get_address - returns address
string get_town() const;
// get_town -returns town
string get_state() const;
// get_state - returns state
int get_postal() const;
// get_postal returns zip code
private:
//member variables
string street;
string city;
string st;
int zip;
};
#endif // ADDRESSSPACE_H_INCLUDED
AddressSpace.cpp
#include "AddressSpace.h"
AddressSpace::AddressSpace(string address, string town, string state, int postal){
string street = address;
string city = town;
string st = state;
int zip = postal;
}
string AddressSpace::get_address() const {
return street;
}
string AddressSpace::get_town() const {
return city;
}
string AddressSpace::get_state() const {
return st;
}
int AddressSpace::get_postal() const {
return zip;
}
The following line of code in main() is a function declaration or prototype.
AddressSpace ob(string address,string town,string state,int postal);
If you remove the type names inside the parentheses it will do what you intended, to construct an object named ob using the given parameters.
AddressSpace ob(address, town, state, postal);
When declaring a new object you don't prefix it with the type. You also haven't instantiated the strings or integer. In C/C++ un-instantiated values are random, so it's good practice to give every variable a default value. You should also include the code for AddressSpace.h and AddressSpace.cpp so we have a better idea of what else could be going wrong
Also, notice the change to the parameters of main(). It's not necessary, but considered good form to always include it. These arguments are filled in with the number of arguments and the arguments themselves if your program is run from the command line.
Your code should look more like this I think:
#include <iostream>
#include <string>
#include "AddressSpace.h"
//#include "AddressSpace.cpp" //This line isn't needed, you should only include the header file
using namespace std;
int main(int argc, char** argv)
{
string address = "";
string town = "";
string state = "";
int postal = 0; //Note postal codes for Europe include letters, and you most-likely won't be doing math with a zipcode so it might make more sense to make it a string
cout << "What is the street you live on?:" << endl;
cin >> address;
cout << "What is the city you live in?:" << endl;
cin >> town;
cout << "What is the state you live in?:" << endl;
cin >> state;
cout << "What is the postal code?:" << endl;
cin >> postal;
AddressSpace ob(address, town, state, postal);
cout << "Address " << ob.get_address(); << endl;
return 0;
}

Display their names in ascending order with respect to their ages?

The stated problem is "Write a program that takes names and ages of 10 employees as input in a 2D char array and display their names in ascending order with respect to their ages".
I've pasted below what I have so far, but I don't know how to display the names in ascending order with respect to age. What am I missing?
#include<iostream.h>
#include<string.h>
void sort(int[],int);
void main(void)
{
char a[10][5],x;
int b[5],i,j;
for(j=0;j<=5;j++)
{
cout<<"Enter name of Employee:";
for(i=0;i<10;i++)
{
cin>>x;
x=a[j][i];
}
cout<<"Enter Employee's age:";
cin>>b[j];
cout<<endl;
}
sort(b,j);
cout<<"Name of Employee \t\t Age \n";
for(j=0;j<5;j++)
{
for(i=0;i<10;i++)
{
x=a[j][i];
cout<<"\t"<<x;
}
cout<<"\t\t"<<b[j]<<"\n";
}
}
void sort(int x[],int size)
{
int temp,i,j;
for(j=0;j<size;j++)
{
for(i=0;i<size;i++)
{
if(x[i]>x[i+1])
{
temp=x[i+1];
x[i+1]=x[i];
x[i]=temp;
}
}
}
}
I will point you in the right direction.
You should define struct to hold a Name and age pair, then make a comparison function.
Then you simply need to populate a vector of your structs then sort them using the sorting function provided by the standard library, iterate through the vector printing out the contents, you can define stream operator of the struct you made to simplify them.
http://www.cplusplus.com/doc/tutorial/structures/
http://en.cppreference.com/w/cpp/algorithm/sort
http://en.cppreference.com/w/cpp/container/vector
http://www.java2s.com/Code/Cpp/Overload/Overloadstreamoperator.htm
EDIT: and please for all that is good, use a std::string to hold the names.
http://www.cplusplus.com/reference/string/string/
using an char array like you are is pretty much deprecated.
I started writing this before the other solution, because I would rather see what C++ is capable of not what your lecture is feeding you.
#include <string>
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <fstream>
struct employee
{
employee(const std::string& name_, unsigned age_)
: name(name_), age(age_) {}
std::string name;
unsigned age;
};
std::ostream& operator<<(std::ostream& os, const employee& e)
{
os << e.name << " " << e.age;
return os;
}
bool comp_age(const employee& e1, const employee& e2)
{
return e1.age<e2.age;
}
int main()
{
std::vector<employee> employees;
employees.reserve(5);
for(unsigned i=0; i!=5; ++i)
{
std::string name;
unsigned age;
std::cout << "Name:" << std::flush;
std::cin >> name;
std::cout << "Age:" << std::flush;
if(!std::cin >> age)
{
std::cerr << "not an number" << std::endl;
--i;
continue;
}
//note you should catch any failure to parse to int here
employees.push_back(employee(name, age));
}
std::sort(employees.begin(), employees.end(), comp_age);
std::copy( employees.begin(), employees.end(),
std::ostream_iterator<employee>(std::cout, "\n"));
return 0;
}
So this is an alternative, but PLEASE learn the concepts I list above which constitutes this example.
You should start by changing void main to int main, because void main is not valid C++. Then you change the #includes to be real C++ header files not what you have:
#include <iostream>
#include <string>
Then you should give meaningful names to your variables. It's impossible to follow the code in a sea of as and bs.
Then you need to sort the employees by their age. You already have a sorting algorithm written there, so you only need to adapt it to swap all the employee data instead of swapping just their ages, while still doing the comparisons only on their age. This will be easier if instead of two separate arrays for the employee data, you kept instead a single array of a structure that holds both the name and age of the employee:
struct employee {
std::string name;
int age;
};
Once sorted, you can just loop through all the employees an print their names.
I believe there are a few more issues in the code, but they should be easy to fix with a good reference and some debugging time. If you have trouble, you can post a new question with what you've got so far, and explain what is stumping you.
This would all be much better if you just used the C++ standard library, but unfortunately some teachers decide to teach Crippled++ to their students instead of proper C++ :(
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
// treat an employee as a single unit
struct employee {
std::string name;
int age;
};
// a comparison function to compare two employees by their age
// should return true if the first one is younger than the second one
// this will be used for sorting later
bool is_younger(employee const& l, employee const& r) {
return l.age < r.age;
}
int main()
{
// a vector with 5 employees
std::vector<employee> employees(5);
for(j=0;j<=5;++j)
{
std::cout << "Enter name of Employee: "
// read the entire name at once
getline(std::cin, employees[j].name);
std::cout << "Enter Employee's age:";
// read the age
std::cin >> employees[j].age;
}
// sort all the employees using the comparison function written above
std::sort(employees.begin(), employees.end(), is_younger);
std::cout<<"Name of Employee \t\t Age \n";
for(j=0;j<5;++j)
{
std::cout << employees[j].name;
std::cout << "\t\t" << employees[j].age << "\n";
}
}
Use a std::multimap (a key/value store, fitting your needs), which is weakly sorted ascending by default. Your key is the age and the value is the name. For printing the values just use iterators. std::multimap is chosen because there could potentially be employees with the same age.
#include <iostream.h>
int main() {
int a;
int b;
int sum;
std::cout << "Enter two numbers" << std::endl;
std::cout << "Enter the value of a" << std::endl;
std::cin >> a;
std:: cout << "Enter the value of b" << std::endl;
std::cin >> b;
sum = a + b;
std::cout << sum << std::endl;
return 0;
}