【问题标题】:cin.getline skips the reminder of the input if the user enters larger input than the char array如果用户输入的输入大于 char 数组,cin.getline 会跳过输入提示
【发布时间】:2019-09-29 06:59:41
【问题描述】:

我正在尝试将数据输入到一个结构数组中,该数组包含一个 char 数组成员和一个 int 成员,如下所示:

int main(){
    typedef struct {
        char name[10];
        int age;
    }Student;
    Student students[3];
    for (i=0;i<N;i++){
        cout<<"\n Enter name of student : "<< i+1<<" " ;
        cin.getline(students[i].name, 10);
        cout<<"\n Enter age of student : "<< i+1<<" ";
        cin>>students[i].age ;    
    }

但如果我输入的名称超过 10 个字符(用户可能会这样做),则输入命令的其余部分将被忽略。

我尝试添加cin.ignore(),但没有帮助。

我尝试将gets(students[i].name);fflush(stdin); 一起使用,但这也无济于事。

我不能使用std::string。有什么建议么?

【问题讨论】:

    标签: c++ cin getline


    【解决方案1】:

    我刚刚想起了文档。 std::istream::getline():

    如果函数没有提取字符(例如,如果 count

    这意味着在输入超过 10 个字符(包括 EOL)后,std::cin 处于失败状态。因此,如果不对此做出反应,就无法提取更多输入。

    您可以通过std::istream::fail() 进行检查。

    要清除失败状态,可以使用std::istream::clear()

    在准备 MCVE 时,我发现了另一个弱点:

    std::istream::getline() 与输入流运算符&gt;&gt; 混合需要特别小心,因为

    • getline() 读取到行尾分隔符但是
    • operator&gt;&gt; 在实际值之前读取空格(包括行尾)。

    因此,ignore() 应该在 getline() 出错后使用以丢弃行的其余部分,但 ignore() 应该始终在 std::cin &gt;&gt; students[i].age 之后使用以消耗行尾,至少。

    所以,我想出了这个:

    #include <iostream>
    
    int main()
    {
      const unsigned N = 3;
      const unsigned Len = 10;
      struct Student {
        char name[Len];
        int age;
      };
      Student students[N];
      for (unsigned i = 0; i < N; ++i) {
        std::cout << "Enter name of student " << i + 1 << ": ";
        std::cin.getline(students[i].name, Len);
        if (std::cin.fail()) {
          std::cerr << "Wrong input!\n";
          std::cin.clear();
          std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
        std::cout <<"Enter age of student : " << i + 1 << " ";
        std::cin >> students[i].age;
        if (std::cin.fail()) {
          std::cerr << "Wrong input!\n";
          std::cin.clear();
        }
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
      }
      // check read
      std::cout << "\nStudents:\n";
      for (unsigned i = 0; i < N; ++i) {
        std::cout << i + 1 << ".: "
          << "name: '" << students[i].name << "'"
          << ", age: " << students[i].age << "\n";
      }
    }
    

    输入/输出:

    Enter name of student 1: Johann Sebastian
    Wrong input!
    Enter age of student 1: 23
    Enter name of student 2: Fred
    Enter age of student 2: 22
    Enter name of student 2: Fritz
    Enter age of student 2: 19
    
    Students:
    1.: name: 'Johann Se', age: 23
    2.: name: 'Fred', age: 22
    3.: name: 'Fritz', age: 19
    

    Live Demo on coliru

    【讨论】:

      猜你喜欢
      • 2021-03-25
      • 2012-04-29
      • 1970-01-01
      • 2014-03-08
      • 1970-01-01
      • 2014-04-07
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      相关资源
      最近更新 更多