gpt4 book ai didi

C++ cin.getline 似乎被跳过

转载 作者:行者123 更新时间:2023-11-30 01:59:26 24 4
gpt4 key购买 nike

我不太明白为什么我下面的程序会跳过“cin.getline(staffMember, 100);”。例如,如果我添加像“q”这样的分隔符,它会按预期工作。我不确定为什么它会自动输入新行。有人可以向我解释为什么会这样吗?

#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream> // Allow use of the ifstream and ofstream statements
#include <cstdlib> // Allow use of the exit statement

using namespace std;

ifstream inStream;
ofstream outStream;

void showMenu();
void addStaffMember();

void showMenu()
{
int choice;

do
{
cout
<< endl
<< "Press 1 to Add a New Staff Member.\n"
<< "Press 2 to Display a Staff Member.\n"
<< "Press 3 to Delete a Staff Member.\n"
<< "Press 4 to Display a Report of All Staff Members.\n"
<< "Press 5 to Exit.\n"
<< endl
<< "Please select an option between 1 and 5: ";

cin >> choice;

switch(choice)
{
case 1:
addStaffMember();

break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
cout << "You did not select an option between 1 and 5. Please try again.\n";
}
} while (choice != 5);
}

void addStaffMember()
{
char staffMember[100];

cout << "Full Name: ";

cin.getline(staffMember, 100);

outStream.open("staffMembers.txt", ios::app);
if (outStream.fail())
{
cout << "Unable to open staffMembers.txt.\n";
exit(1);
}

outStream << endl << staffMember;

outStream.close();
}

int main()
{
showMenu();

return 0;
}

最佳答案

当用户输入一个选项时,他们会键入一个数字,然后按回车键。这会将包含 \n 字符的输入放入输入流中。当您执行 cin >> choice 时,将提取字符直到找到 \n,然后这些字符将被解释为 int。但是,\n 仍在流中。

稍后,当您执行 cin.getline(staffMember, 100) 时,它会读取到 \n 并且看起来好像您输入了一个新行而没有实际输入任何东西。

为了解决这个问题,使用 ignore 提取到下一个新行:

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

这将提取直到并包括下一个 \n 字符的所有内容并将其丢弃。所以实际上,当用户输入类似 1banana 的内容时,这甚至会处理。 1 将由 cin >> choice 提取,然后该行的其余部分将被忽略。

关于C++ cin.getline 似乎被跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16278038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com