fgets()没有接受输入

时间:2018-02-25 07:01:32

标签: c++ fgets getline gets

我使用fgets(learner.name,21,stdin)来输入学生的名字,但是当我运行该程序时,它会显示"输入你的姓名"并跳至"在5个科目中输入您的分数。 "

有人可以解释我为什么会这样吗?因为它与cin.getline()函数相同。

gets_s()函数不工作编译器显示" ' gets_s'未在此范围内宣布"

#include<iostream>
#include<stdio.h>
#include<cstdlib>
using namespace std;
struct Student
{
    int rollno;
    char name[21];
    float marks[5];
    char grade;
};
Student learner ;
int main()
{
    cout<<"\n"<<"Enter Roll number: ";
    cin>>learner.rollno;
    cout<<"\n"<<"Enter your name: ";
    fgets(learner.name,21,stdin);
    cout<<"\n"<<"Enter your marks in 5 subjects: "<<"\n";
    for(int i = 0;i <5;++i)
    {
        cout<<"\n"<<"Subject"<<i+1<<":";
        cin>>learner.marks[i];
    }
    float avg ,total;
    total =  (learner.marks[0]+learner.marks[1]+learner.marks[2]+learner.marks[3]+learner.marks[4]);
    avg = total/5;
    if(avg<50)
        learner.grade = 'D';
    else if(avg<60)
        learner.grade = 'C';
    else if(avg<80) 
        learner.grade = 'B';
    else
        learner.grade = 'A';
    cout<<"\n"<<"\n"<<"Student result: \n";
    cout<<"Roll Number: "<<learner.rollno<<"\t";
    cout<<"Name: ";
    cout.write(learner.name,21);
    cout<<"\n"<<"Total Marks: "<<total;
    cout<<"\t"<<"Grade: "<<learner.grade<<endl;
    system("pause");
    return 0;
}

这是输出:

  Enter Roll number: 22
  Enter your name:
  Enter your marks in 5 subjects:

  Subject1:

0 个答案:

没有答案