【问题标题】:Why some of the string variable not taking inputs from structure to void function? [duplicate]为什么某些字符串变量不从结构中获取输入到 void 函数? [复制]
【发布时间】:2021-02-11 19:01:53
【问题描述】:

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

预期输出

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

1.新增学生

2.新增教师

3.新增通知

1

输入学生的名字:结婚

输入学生的姓氏:lisa

输入学生卷号:245

进入学生区:C

输入学生的年级:1

输入学生的学期:2

输入学生所在部门:IR

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

输入学生电话:15648955

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

立即输出

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

1.新增学生

2.新增教师

3.新增通知

1

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

输入学生卷号:245

输入学生的部分:输入学生的年份:1

输入学生的学期:2

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

输入学生电话:15648955

输入学生地址:

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

#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();
}

【问题讨论】:

  • 请缩进您的代码以提高可读性。
  • @ThomasSablik 不,它不符合我需要的东西
  • 骗子中描述的解决方案是:调用std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n')毕竟cin&gt;&gt;...;
  • 电话号码也不是问题的一部分。
  • “电话号码也不是问题的一部分” 那么你不应该把它发到你的minimal reproducible example

标签: c++ string c++11 structure


【解决方案1】:
cin>>stu.Phone;

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

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 2012-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多