将Struct传递给函数并在其中输入数据

时间:2014-04-02 18:49:35

标签: c++ c

我有一个结构数组,我尝试将一个元素传递给输入数据,我想要修改数组,所以我将它作为指针传递但是当我通过scanf输入数据时出现问题所以程序是'正在运行

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

#define n 50

struct Student
{
    char *FirstName;
    char *LastName;
    double Grade;
};

void StudentData( struct Student st );
void EnterStudentData ( struct Student *st );
void AddStudent ( struct Student *st, int *size );

int main()
{
    int size = 0;
    struct Student students[n];

    AddStudent(students, &size);
    StudentData(students[0]);

    return 0;
}

void StudentData( struct Student st )
{
    printf("FirstName: %s\tPrenume: %s\tMedia: %.2lf", st.FirstName, st.LastName, st.Grade);
}

void EnterStudentData ( struct Student *st )
{
    printf("FirstName : ");
    scanf_s("%s", &st->FirstName);
    printf("LastName : ");
    scanf_s("%s", &st->LastName);
    printf("Grade : ");
    scanf_s("%lf", &st->Grade);
}

void AddStudent ( struct Student *st, int *size )
{
    EnterStudentData(&st[*size]);
    ++(*size);
}

2 个答案:

答案 0 :(得分:2)

您尚未为FirstNameLastName

分配任何内存

试试这个:

char FirstName[n];
char LastName[n];

但如果你正在使用C ++,只需使用string

修改

由于您使用C ++标记了问题,因此这是一个包含stringvector的C ++解决方案:

#include <string>
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;

struct Student
{
  string FirstName;
  string LastName;
  double Grade;
};

void StudentData( const Student& _st );
void EnterStudentData ( Student& _st );
void AddStudent ( vector<Student>& st, int& size );

int main()
{
  int size = 0;
  vector<Student> students;

  AddStudent(students, size);
  StudentData(students[0]);

  return 0;
}

void StudentData( const Student& _st )
{
   cout << "FirstName: " << _st.FirstName << "\t"
        << "LastName: " << _st.LastName << "\t";
   cout.setf(ios::fixed,ios::floatfield);
   cout.precision(2);
   cout << "Grade: "  << _st.Grade << endl;
}

void EnterStudentData (Student& _st )
{
  cout << "FirstName : ";
  cin >> _st.FirstName;
  cout << "LastName : ";
  cin >> _st.LastName;
  cout << "Grade : ";
  cin >> _st.Grade;
}

void AddStudent (vector<Student>& _st, int& _size )
{
  Student next;
  EnterStudentData(next);
  _st.push_back(next);
  ++_size;
}

答案 1 :(得分:-2)

使用scanf_s(“%s”,&amp; st-&gt; FirstName),获取st的地址并使用 - &gt;操作员就可以了。尝试使用&amp;(st-&gt; Grade)