简体   繁体   English

在结构指针方面需要帮助

[英]Need help in structure pointers

In c++ I have to make a program where I have to write a menu driven program to input, edit or display the name, id and cgpa of a student. 在c ++中,我必须编写一个程序,在该程序中,我必须编写一个菜单驱动程序来输入,编辑或显示学生的姓名,ID和cgpa。 The code is as follows: 代码如下:

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;

struct student
{
    char name[20];
    int id;
    float cgpa;
};

void input(struct student *);
void display(struct student *);
void edit(struct student *);

int main()
{
    int ch;
    struct student a;

    while(ch!=4)
    {
        cout<<"1.input";
        cout<<"\n2.edit";
        cout<<"\n3.display";
        cout<<"\n4.exit";
        cout<<"\nenter your choice";
        cin>>ch;
        if(ch==1)
        {
            cout<<"enter name, id and cgpa of student\n";
            input(&a);
        }
        else if(ch==2)
        {
            cout<<"enter new name, id and cgpa  of the student\n";
            edit(&a);
        }
        else if(ch==3)
        {
            display(&a);
        }
        else if(ch==4)
        {
            ch=ch;
        }
        else{cout<<"wrong choice\n";}
    }

    return 0;
}

void input(struct student *s)
{
    cin>>s->name;
    cin.ignore(256,'\n');
    cin>>s->id;
    cin>>s->cgpa;
}

void edit(struct student *s)
{
    cin>>s->name;
    cin.ignore(256,'\n');
    cin>>s->id;
    cin>>s->cgpa;
}

void display(struct student *s)
{
    cout<<s->name<<"\n";
    cout<<s->id<<"\n";
    cout<<s->cgpa<<"\n";
}

But whenever I am inputting a name through cin.getline() function, it doesn't display a name on the screen. 但是,每当我通过cin.getline()函数输入名称时,它都不会在屏幕上显示名称。 Instead a blank space is left there and id and cgpa are printed. 而是在此处留有空白,并打印id和cgpa。 Cin is working fine but cin does not take a space. Cin工作正常,但cin不占空间。 What is wrong in the code that it is not printing the name while using cin.getline(). 使用cin.getline()时未打印名称的代码有什么问题。

Call cin.ignore() before calling cin.getline() 在调用cin.ignore()之前先调用cin.getline()

Or 要么

make a dummy call cin.getline() to consume the trailing newline character from the cin 进行虚拟调用cin.getline()以使用cin的尾随换行符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM