如何在 do-while 循环中使用 getline?

我的地方康
#include <iostream>
#include<algorithm>
#include<string>
using namespace std;

struct student {
    string name;
    int number;
    double score;
};

bool compare(const student& a, const student& b)  {
    return a.score > b.score;
}

int main()
{
    // int x = 10;
    struct student stu[x];
    int i = 0;

    /** for(i = 0; i<x; i++) {
        cout<<"Please enter the name.: ";
        getline(cin, stu[i].name,'\n');
        cout<<"Please enter the student number.: ";
        cin>>stu[i].number;
        cout<<"Please enter the score.: ";
        cin>>stu[i].score;
        cin.ignore();
    } **/

    do {
        cout<<"Please enter the name.: ";
        getline(cin, stu[i].name,'\n');
        cout<<"Please enter the student number.: ";
        cin>>stu[i].number;
        cout<<"Please enter the score.: ";
        cin>>stu[i].score;
        i++;
        cin.ignore();
    } while (stu[i].name == "quit");

    sort(stu, stu+x, compare);

    cout<<"Rank"<<'\t'<<"Name"<<'\t'<<"Student Number"<<'\t'<<"Score"<<endl;
    for(int j = 0; j<x; j++) {
        cout<<j+1<<'\t'<<stu[j].name<<'\t'<<stu[j].number<<'\t\t'<<stu[j].score<<endl;
    }
}

要使用 for 循环,我需要知道学生人数,但如果我不知道人数,我想使用 do-while 循环并且它必须运行直到我输入“退出”。但现在它发生了错误。我猜 stu[i].name == "quit" 是问题所在,我该如何解决?

丘里尔

我建议以下内容使您的代码更安全并使用现代 C++。

  • 将所有数据读入一个临时变量,这样你就不会得到一个名为“退出”的学生。
  • 检查每次读取是否成功,如果没有,则退出循环。
  • 使用std::vectorpush_back每个学生而不是依赖固定大小的数组。

std::vector<student> stu;

do {
    student input;

    std::cout << "Please enter the name.: ";
    if (!std::getline(std::cin, input.name, '\n') || input.name == "quit") {
        break;
    }

    std::cout << "Please enter the student number.: ";

    if (!(std::cin >> input.number)) {
        break;
    }

    std::cout << "Please enter the score.: ";

    if (!(std::cin >> input.score)) {
        break;
    }

    // At this point all reading was successfull
    stu.push_back(input);

    std::cin.ignore();
} while (true); // Exit conditions are covered inside the loop

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章