使用 getline 在 C++ 中输出整个字符串

output the whole string in c++ using getline

本文关键字:字符串 输出 getline C++ 使用      更新时间:2023-10-16

我写了这段代码。它在主函数中工作

cout << "Enter the patron's name: ";
getline(std::cin, patron.name);
cout << "Enter the book title: ";
getline(std::cin, book.title);
cout << book.title << " is now checked out to " << patron.name << endl;

但是,当我将其放在带有开关盒的 do while 循环下时,它不再起作用。

do {
        cout << endl << "? "; cin >> choice;
        switch (toupper(choice)){
        case 'T':           
            cout << "Enter the patron's name: ";
            getline(std::cin, patron.name);
            cout << "Enter the book title: ";               
            getline(std::cin, book.title);
            cout <<  book.title << " is now checked out to " << patron.name << endl;
            break;
           }[enter image description here][1]
} while (choice != 'Q' && choice!= 'q');

输入如下:

谁能向我解释为什么会这样?谢谢

在此语句之后

cout << endl << "? "; cin >> choice;

插入

std::cin.ignore( std::numeric_limits<std::streamsize>::max(), 'n' );

删除仍在输入缓冲区中的换行符(对应于输入后按下的 Enter 键),否则调用 getline 将读取空字符串。

应包含标头<limits>以使用该类numeric_limits

这个n T(你的输入)被getline消耗。这就是为什么你会有这样的行为。您需要将换行符从缓冲区中冲出。

您可以通过添加此语句来执行此操作,如下所示。

std::cin.ignore (std::numeric_limits<std::streamsize>::max(), 'n');
cout << "Enter the patron's name: ";