How can I pass this structure into the available functions? - c++

I need help passing a structure through a function to collect and print out its corresponding information. When I try and run the code below the compiler returns that I have too many arguments for the functions.
#include <iostream>
using namespace std;
int num;
void getInput();
void classBank();
struct Record
{
string fname, sname;
int marks, indexNum;
double average;
};
int main()
{
Record student;
getInput();
classBank(student);
}
void getInput()
{
cout<<"How many people are you dealing with: ";
cin >> num;
}
void classBank(struct student)
{
for(int i = 1; i < num; i++)
{
cin >> student[i].fname;
cin >> student[i].sname;
cin >> student[i].marks;
cin >> student[i].indexNum;
cin >> student[i].average;
}
}

Replace
void getInput();
void classBank();
with
void getInput();
void classBank(Record student);
EDIT:
That code won't work 'cause of several reasons:
You declare functions that use struct Record, before declaration of Record
You do not understand what keyword struct means
You pass single element (without overloaded []), not an array to the classBank
EDIT2 Typo

Related

Difficulty in understanding c++ string literals

Here the below code is my some part of my program. It doesn't execute it says c++ forbids converting string constants to char*.How can I fix this error?
#include <cstring>
#include <iostream>
using namespace std;
class Bank
{
private:
char name[20];
int acc;
float amount;
public:
Bank()
{
strcpy("",name);
acc = 0;
amount = 0;
}
void open(int a)
{
cout << "Enter name:";
cin >> name;
acc = a;
cout << "Enter Amount" << endl;
cin >> amount;
}
void edit(int flag, float a);
};
int main()
{
Bank B[10];
}
std::strcpy("", name); needs to be std::strcpy(name, "");
Although, setting aside the fact that std::string would be a far better type for name (the future King of England, Charles Mountbatten-Windsor, would not be able to be a customer), writing
name[0] = 0;
would be sufficient.

Why is the syntax for taking the input about name not working?

#include<iostream>
#include<string>
using namespace std;
class data{
string name;
string code;
public :
void getname()
{
cout<<"Enter name : ";
getline(cin,name);
}
void getcode()
{
cout<<"Enter code : ";
getline(cin,code);
}
void display()
{
cout<<"Name : "<<name;
cout<<"Code : "<<code;
}
};
int main()
{
int n,i=0; cin>>n;
data stud[n];
while(i<n)
{
stud[i].getname();
stud[i].getcode();
i++;
}
for(int i=0;i<n;i++)
stud[i].display();
return 0;
}
In Line 13: The getline() is not executed. Can anyone explain its cause and an alternative?
Initially, I thought that I may have missed a header file or the syntax is wrong, but that is not the case as the syntax for input of code works just fine.
When using cin and getline function alternatively, you should clear the cin input stream. by using cin.ignore() funtion.
Here I am using cin.ignore() after your cin statements because you want to ignore the "\n" left in the buffer after taking your int variable with cin.
#include<iostream>
#include<string>
using namespace std;
class data{
string name;
string code;
public :
void getname()
{
cout<<"Enter name : ";
getline(cin,name);
}
void getcode()
{
cout<<"Enter code : ";
getline(cin,code);
}
void display()
{
cout<<"Name : "<<name;
cout<<"Code : "<<code;
}
};
int main()
{
int n,i=0;
cin>>n;
cin.ignore();
data stud[n];
while(i<n)
{
stud[i].getname();
stud[i].getcode();
i++;
}
for(int i=0;i<n;i++)
stud[i].display();
return 0;
}
Hope This Might Helps: )
For starters there is a typo in this function
void getname()
{
cout<<"Enter name : ";
getline(cin,code);
^^^^
}
And this declaration of the array
int n,i=0; cin>>n;
data stud[n];
is invalid. The variable n is not initialized and variable length arrays is not a standard C++ geature.

Passing a variable from main into a public class function?

I was wondering how in this situation I can pass a variable from main into a public class function. In this situation the health variable doesn't change at all even though it should. Here's my code:
class PlayerCharacter
{
public:
void SetHealth(int Health)
{
m_health = Health;
}
int GetHealth()
{
return m_health;
}
private:
int m_health;
int m_maxhealth;
};
int main()
{
PlayerCharacter PC;
bool playing = true;
int Choice;
int v1;
int v2;
while (playing)
{
PrintMainMenu();
cout << "Set Health And Max Health" << endl;
cin >> Choice;
v1 = Choice;
cin >> Choice;
v2 = Choice;
PC.SetHealth(v1);
PC.SetMaxHealth(v2);
system("CLS");
}
return 0;
}
Is there something I'm missing here? Thanks.
edit: All of my code
From your code link, your PrintMainMenu() function is creating an entirely new Character each time. It has no relation to the one being edited in main().
You should change it to accept a Character as a reference and use that to print your stats:
void PrintMainMenu(Character& PC) {
...
}
You can try using getline (cin, input) instead of cin>> as reading directly with cin is not type safe and as far as I know, it does not remove newline character. Also, it does not perform length check. So it has been some time not to use C++ but if I remember correctly getline works better.
getline (cin, Choice);
In function void PrintMainMenu() you are creating a new Character.
You need to pass a reference on your Character from main into this function.

C++ Storing a string into a class

I made a topic a bit ago regarding structs. And I know that classes have the same concept as structs. How would I go about storing a string into the class?
This is the class
class studentType
{
public:
void setData(string, int);
string getName() const;
int getId() const;
private:
string name;
int sid;
};
void studentType::setData(string, int) {
name = ??;
sid = ??;
}
string studentType::getName() const {
return name;
}
int studentType::getId() const {
return sid;
}
The main consists of:
int main() {
studentType object, number;
cout << "enter name and code of item1: ";
cin >> object.setData() >> object.setData();
cout << "enter name and code for item2: ";
cin >> number.setData() >> number.setData();
system("pause");
return 0;
}
How would I fix the cin issue? I already have string defined in the header. And yes, I know using namespace std; isn't preferred but it's for simplicity
int id;
string name;
cout << "enter name and code of item1: ";
cin >> name >> id;
object.setData(name, id);
cout << "enter name and code for item2: ";
cin >> name >> id;
object.setData(name, id);
You should instead use a constructor for your class though:
class studentType {
public:
studentType(string name, int sid)
: name(name)
, sid(sid)
{ }
// ...
You can then initialize your objects with the correct name and ID:
cin >> name >> id;
studentType object(name, id);
But I suppose constructors will come up very soon in the tutorial or course you're currently doing.
cin >> object.setData() >> object.setData();
the >> operator doesn't call object.setData; it takes a reference and sets the reference contents to the extracted input. The expression object.setData() calls the function, which returns void. Of course, the >> operator cannot take a void argument. Also, there aren't enough arguments in the funcall because object.setData expects a string and an int.
You should do this:
std::string name;
int num;
cin >> name >> num;
object.setData(name, num);
Your setData function can be as such:
void studentType::setData(string name, int sid) {
this->name = name;
this->sid = sid;
}
And in your main():
First cin the values and then call the setData function, i.e.
int main(){
string name;
int code;
studentType object, number;
cout << "enter name and code of item1: ";
cin >> name >> code;
object = studentType();
object.setData(name, code);
// your remaining code
}
Just a note of caution:
If you use cin to get the name and code, the name can only be a single word. Say if you are writing a name of two words, the first word will be put in name and the second will be attempted to put in code.
In simpler terms, cin is space-delimited.
What you're looking for is std::getline(). I would use cin for getting your integers, but not for the strings. I would separate the user input like this. Like #Suhaib Ahmad said, cin is space-delimited. To get a string including spaces from stdin, use std::getline().
void studentType::setData(string n, int i) {
this->name = n;
this->sid = i;
}
-
int main(void) {
string n;
int i;
studentType object, number;
cout << "Enter name for item1: ";
getline(cin, n);
cout << "Enter code for item1: ";
cin >> i;
object = studentType(); // make sure you construct your studentType, I also recommend using a constructor function
object.setData(n, i);
cout << "Enter name for item2: ";
getline(cin, n);
cout << "Enter code for item2: ";
cin >> i;
number = studentType();
number.setData(n, i);
system("pause");
return 0;
}
The way you are using setData(), with no arguments given, as a place to store the cin input is incorrect. You would need to declare variables first, and then initialize your class with the variables.

Returning a structure pointer

I'm quite new with c++ and need some help with the following code.
#include <iostream>
using namespace std;
struct student {
string name;
int age;
float marks;
};
struct student *initiateStudent(string , int , float);
int main ( ) {
int totalStudents = 1;
string name;
int age;
float marks;
cin >> totalStudents;
student *stud[totalStudents];
for( int i = 0; i < totalStudents; i++ ) {
cin >> name >> age >> marks;
stud[i] = initiateStudent(name,age,marks);
}
cout << stud[0]->name;
return 0;
}
struct student *initiateStudent(string name, int age, float marks)
{
student *temp_student;
temp_student->name = name;
temp_student->age = age;
temp_student->marks = marks;
return temp_student;
}
I need in the function initiateStudent return a struct pointer to the pointer array stud by passing the members name, age, marks.
I know that the problem sofar is the fact that temp_student is destroyed when I return to the main file.
So my question is how it could be done by just passing the members of the struct and then return back with information to the pointer array stud.
Thank you very much.
Semi-answer To explain the bad habits:
#include <string>
#include <iostream>
#include <vector>
//using namespace std; often injects subtle bugs. Use with caution
// read more here:
// http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
struct student
{
std::string name; // explicit namespacing reduces possibility of unwanted collisions
int age;
float marks;
//added constructor in place of initialization function.
student(std::string name, int age, float marks):name(name), age(age), marks(marks)
{
}
};
int main()
{
int totalStudents = 1;
std::string name;
int age;
float marks;
while (!(std::cin >> totalStudents)) // testing input for success
// Needed extra brackets caught by M.M
// teach me to not test even a throw-away example
{
std::cout << "must... have... good... input..." << std::endl;
cin.clear(); // clear the error and get rid of any other garbage the user may have input.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
//student *stud[totalStudents]; illegal in C++
std::vector<student *> stud(totalStudents); // using dynamic array instead
for (int i = 0; i < totalStudents; )// i++ removed
{
if (std::cin >> name >> age >> marks) //testing input
{
stud[i] = new student(name, age, marks); // using constructor
i++; // and put here. Only increment if input is valid.
}
else
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}
std::cout << stud[0]->name;
for (student * stu: stud) // cleaning up allocated memory
{
delete stu;
}
return 0;
}
One of the beauties of C++ is you rarely need to self-manage memory. In fact there are huge advantages in not doing it above and beyond not having to clean up after yourself.
#include <string>
#include <iostream>
#include <vector>
struct student
{
std::string name;
int age;
float marks;
student(std::string name, int age, float marks):name(name), age(age), marks(marks)
{
}
};
int main()
{
std::string name;
int age;
float marks;
std::vector<student> stud; // look ma! No pointer!
while (std::cin >> name >> age >> marks) //exits loop on bad input
{
stud.emplace_back(name, age, marks); // building directly in vector
// vector will size itself as needed.
}
std::cout << stud[0].name;
return 0;
}
One more caveat: >> is whiespace delimited. That means it stops when it finds whitespace (space, tab, end of line...) so a name of "John Jacob Jingleheimer-Shmidt" will go into name as "John". >> will then attempt to interpret "Jacob" as age, and that will not go so well.
the simple solution is to make your initiateStudent() creates temp_student on the heap (with new): and returns it. keep in mind heap allocated memory is not freed automatically so don't forget to free it later on yourself.
#include <iostream>
#include <string>
using namespace std;
struct student {
string name;
int age;
float marks;
};
struct student *initiateStudent(string , int , float);
int main ( ) {
int totalStudents = 1;
string name;
int age;
float marks;
cout << "Total student: ";
cin >> totalStudents;
cin.sync(); // very very important to not affect the next input (name)
student* stud = new student[totalStudents];
for( int i = 0; i < totalStudents; i++ )
{
cout << "Name: ";
getline(cin, name);
cin.sync();
cout << "age: ";
cin >> age;
cout << endl;
cout << "Marks: ";
cin >> marks;
cout << endl;
cin.sync();
stud[i] = *initiateStudent(name, age, marks);
}
cout << "Student 1: " << stud[0].name << endl;
delete[] stud;
stud = NULL;
return 0;
}
struct student *initiateStudent(string name, int age, float marks)
{
student *temp_student = new student;
temp_student->name = name;
temp_student->age = age;
temp_student->marks = marks;
return temp_student;
}