【问题标题】:Infinite loop after input输入后无限循环
【发布时间】:2021-03-12 11:34:01
【问题描述】:

所以我一直在做功课,但偶然发现了一个问题。在我为我的程序输入部分日期后,它就会进入一个无限循环。这个想法是创建一个由结构条目组成的数组。我不确定问题似乎来自哪里,因为它刚刚开始打印出“您的选择:”而没有停止。这是我的代码:

        #include <iostream>
    using namespace std;

    struct property {
      int num;
      char nBrok[50];
      char type[10];
      char adress[50];
      char outlook[20];
      double price;
      double size;
      int nRooms;
      int floor;
      char status[2];
    };

    int menu() {
      int ch;
      cout<<"Choose an option from 1-5."<<endl;
      cout<<"1. Add property."<<endl;
      cout<<"2."<<endl;
      cout<<"3."<<endl;
      cout<<"4."<<endl;
      cout<<"5. Exit"<<endl;
      do {
        cout << "\nYour Choice: ";
        cin>>ch;
      } while (ch<1 || ch>5);
      return ch;
    }

    void addProp(property bDanni[]) {
      int count;
      cout<<"1. Add property."<<endl;
      cout<<"How many real estate properties would you like to add?"<<endl;
      cin>>count;
      for(int i=0; i < count; i++)
      {
        cin.ignore();
        cout<<"Enter the entry number of the property: "; cin>>bDanni[i].num;
        cout<<"Enter the name of the property's broker: "; cin.getline(bDanni[i].nBrok, 50);
        cin.ignore();
        cout<<"Enter the type of the property: "; cin.getline(bDanni[i].type, 10);
        cin.ignore();
        cout<<"Enter the adress of the property: "; cin.getline(bDanni[i].adress, 50);
        cin.ignore();
        cout<<"Enter the outlook of the property: "; cin.getline(bDanni[i].outlook, 20);
        cin.ignore();
        cout<<"Enter the price of the property: "; cin>>bDanni[i].price;
        cout<<"Enter the size of the property: "; cin>>bDanni[i].size;
        cout<<"Enter the number of rooms of the property: "; cin>>bDanni[i].nRooms;
        cout<<"Enter the floor of the property: "; cin>>bDanni[i].floor;
        cout<<"Enter the status the property: "; cin.getline(bDanni[i].status, 2);
        cin.ignore();
      }
    }

    int main() {
      property bDanni[100];
        int choice;
        do {
          choice = menu();
          switch (choice) {
            case 1: addProp(bDanni);break;
          }
        }while (choice !=5);

      return 0;
    }

【问题讨论】:

  • 进入无限循环的输入是什么?
  • 输入是 1;3;01;Patrick Brooke
  • 您提供的代码从不打印Your choice is:。请提供实际产生所描述问题的实际代码。
  • 我想你误解了ignore 在混合&gt;&gt;getline 时的帮助。
  • 菜单功能中应该是“你的选择”,对不起,我会在问题中解决它

标签: c++ arrays c struct structure


【解决方案1】:

在使用 cin 后准备使用 getline 时使用 cin.ignore()。因为 cin 将空字符留在缓冲区中。

【讨论】:

  • 不是空字符,而是换行符。
【解决方案2】:

我是个笨蛋,清除缓冲区应该在 getline 之前发生,这是因为 cin 跳过了间隔。很抱歉浪费了任何人的时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-20
    • 2014-12-12
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    相关资源
    最近更新 更多