如何使用cin测试空白行

时间:2012-03-24 12:11:21

标签: c++ arrays structure cstring cin

下面是我用来将学生数据输入到学生结构数组中的函数的代码。我希望循环在我达到极限(n)时终止,这很好,这就是我遇到麻烦,当为学生姓名输入一个空行时?有人有什么建议吗?我正在使用的当前方法不起作用('cin.getline(pa [i] .fullname,SLEN - 1)下面的if语句;')

int getinfo(student pa[], int n)
{
    cout << "\nPlease enter student details:\n\n";

    int i;
    for (i = 0; i < n; i++)
    {
        cout << "Student " << (i + 1) << ": \n";
        cout << "  > Full name: ";
        cin.getline(pa[i].fullname, SLEN - 1);
        if (pa[i].fullname == NULL)
            continue;
        cout << "  > Hobby: ";
        cin.getline(pa[i].hobby, SLEN - 1);
        cout << "  > OOP Level: ";
        cin >> pa[i].ooplevel;;
        cin.get();

        cout << endl;
    }

    cout << "--------------------------------------" << endl;

    return i;
}

2 个答案:

答案 0 :(得分:1)

使用string并使用原子循环更好:

std::string name, hobby, oop;

std::cout << "Name: ";
if (!(std::getline(std::cin, name)) { break; }

std::cout << "Hobby: ";
if (!(std::getline(std::cin, hobby)) { break; }

std::cout << "OOP: ";
if (!(std::getline(std::cin, oop)) { break; }

// if we got here, everything succeeded.
pa[i].name = name; pa[i].hobby = hobby; pa[i].oop = oop;

// or better, pass a `std::vector<student> &`:
pa.push_back(student(name, hobby, oop));

答案 1 :(得分:0)

getline()读取空行的空行。请注意,您始终检查输入是否成功。我个人也会使用std::string