为什么一些字符串变量不接受从结构到 void 函数的输入?

Why some of the string variable not taking inputs from structure to void function?

在下面的代码中,一些字符串正在接受输入,但有些只是跳过。我检查了一切没有发现任何东西。如果你让我知道我哪里出错了,那将是理想的选择。我需要指出的是,在这个问题上我还有很多工作要做,这就是我创建函数的原因

预期输出

:::::::::::::::::::::::::: 从下面选择选项 ::::::::::::::::::::::::::

1.for 添加新学生

2.for添加新老师

3.for 添加新通知

1

输入学生的名字:Marry

输入学生的姓氏:lisa

输入学生名册号:245

进入学生组:C

输入学生年级:1

输入学生学期:2

输入学生所在部门:IR

输入学生邮箱:lisa2@hotmail.com

输入学生的phone:15648955

输入学生地址:2/A XYZ street

现在输出

:::::::::::::::::::::::::: 从下面选择选项 ::::::::::::::::::::::::::

1.for 添加新学生

2.for添加新老师

3.for 添加新通知

1

输入学生的名字:输入学生的姓氏:lisa

输入学生名册号:245

输入学生部分:输入学生年级:1

输入学生学期:2

输入学生所在部门:输入学生邮箱:lisa2@hotmail.com

输入学生的phone:15648955

输入学生地址:

进程返回 0 (0x0) 执行时间:52.725 秒 按任意键继续。

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

struct student{
    string firstName;
    string lastName;
    int Roll;
    string Section;
    int Year;
    int Semester;
    string Department;
    string Email;
    int Phone;
    string Address;
};

void student_part(void){
    struct student stu;
    cout<<"Enter student's first name :";
    getline(cin,stu.firstName);
    cout<<"Enter student's last name :";
    getline(cin,stu.lastName);
    cout<<"Enter student's roll no :";
    cin>>stu.Roll;
    cout<<"Enter student's section :";
    getline(cin,stu.Section);
    cout<<"Enter student's year :";
    cin>>stu.Year;
    cout<<"Enter student's semester :";
    cin>>stu.Semester;
    cout<<"Enter student's department :";
    getline(cin,stu.Department);
    cout<<"Enter student's email :";
    getline(cin,stu.Email);
    cout<<"Enter student's phone :";
    cin>>stu.Phone;
    cout<<"Enter student's address :";
    getline(cin,stu.Address);
}



void add_info(void){
    int choice;
    cout<<"::::::::::::::::::::::::::"<<endl;
    cout<<" Choose Option From Below"<<endl;
    cout<<"::::::::::::::::::::::::::"<<endl;
    cout<<"\n1.for add new student"<<endl;
    cout<<"2.for add new teacher"<<endl;
    cout<<"3.for add new notice"<<endl;
    cin>>choice;
    if(choice==1){
        student_part();
    }
}


int main()
{
    add_info();
}

cin>>stu.Phone;

正在从命令行获取一个整数,因此它不会读取末尾的 \n 字符,getline 紧接着读取该字符。

getline 之前,写 fgetc(stdin) 以阅读更新。

另一种可能性是将所有 getLine() 函数更改为 cin>>stu... 调用。

错误发生,因为cin 方法没有从输入缓冲区中取出\n。下面的 getLine 从输入 Buffer 中取出剩余的 \n 并立即终止。