使用 getline 在 C++ 中输出整个字符串
output the whole string in c++ using getline
我写了这段代码。它在主函数中工作
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: ";
相关文章:
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 如何在 C++ 中将双精度数组中的值"force convert"到字符串输出中?
- 尝试从 Visual Studios C++ 中的加密字符串输出解密字符串时出现逻辑错误
- C++添加到字符串(输出)
- 如何将非空终止字符串输出到 iostream,但保持格式
- 有没有一种简单的方法可以将矢量 int 集转换为字符串输出?
- 为什么将字符串输出到未命名的 std::ofstream 反而给了我一个十六进制数?
- CodeBlocks字符串输出定界线
- 如何获得字符串输出的宽度
- 为什么 cout 使用 << 生成正确的字符串输出,而不是使用 +?
- 是通过std :: Wostream定义的char*字符串输出
- 简单的字符串输出不符合预期(出现换行符)
- 使用字符串输出特定答案
- 如何在C++中从十六进制字符串输出 Unicode 字符
- 如何获取md5sum命令并获取代码中的字符串输出
- 需要帮助格式化字符串输出
- 快速C++字符串输出
- 与具有字符串输出参数的 WinAPI 函数的一致性是多少
- 用C++将二进制字符串输出到二进制文件
- Linux控制台的国际UTF-32字符串输出