I am working on a program and part of it requires me to create a struct called DETAILS with the fields name, age, and height. I want to populate the record with data using a function argument. I had numerous problems with this code and had lots of help from here but need a little more. I can’t output the populated struct to the screen. If anyone could help me with this last thing I would be so grateful!
Here is my code:
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
const int LEN=100;
struct DETAILS
{
char name[LEN];
int age;
double height;
};
DETAILS fillperson(struct DETAILS David, const char[LEN], int, double);
int main()
{
struct DETAILS David;
fillperson(struct DETAILS David, "David Greene", 38, 180.0);
cout<<David.name<<endl;
cout<<David.age<<endl;
cout<<David.height<<endl;
return 0;
}
DETAILS fillperson(struct DETAILS David, char name[LEN], int age, double height)
{
cout<<"Done"<<endl;
return;
}
This is because string literals (like “David Greene”) are
const, and you’re passing it as just achar[LEN]. Tryconst char[LEN].The
[]goes after the name of the variable:char name[LEN].Also, where is this
Davidvariable coming from? The name of the variable needs to be in the function signature (struct DETAILS David, not juststruct DETAILS).I think what you really want is:
EDIT:
I think you misunderstood what I was saying. This line is a weird mix of function definition of function call.
When you call a function, you don’t declare types:
But you do need them in the actual function definition, so instead of this:
Do this:
EDIT 2:
Also, I don’t know what you’re trying to do here (or any of the similar lines):
Are you trying to copy the string? (See strncpy) or read input (
cin >> David.name)?Recommendation
If you’re using C++ and C++ input streams, you should really just use
string.EDIT 3
Your current code won’t work for several reasons:
The function signature says the function returns
DETAILS(the first part of the line), but you don’t return anything. Either return the input struct:Or make the method return
void(nothing):My recommendation about using
stringis that it’s much easier to work with than straight character arrays (char[]):string name = “David”;
string name2 = name; // Copying is much easier
So for example, your code could look like this: