gpt4 book ai didi

c++ - getline() 不等待 switch 内的输入...case (C++)

转载 作者:行者123 更新时间:2023-11-28 07:21:03 25 4
gpt4 key购买 nike

我正在尝试使用 getline() 从用户那里获取输入。

下面的代码工作正常。它等待用户键入文件名并将其存储在 fileName 中。

#include <iostream>
#include <string>

using namespace std;

string inputFile();

int main()
{
string fileName;
cout << "Enter the name of the file including the path" << endl;
getline(cin, fileName);

return 0;
}

但是,这段代码不能正常工作。

#include <iostream>
#include <string>

using namespace std;

string inputFile();

int main()
{
int option;

cout << "Enter option number" << endl;
cin >> option;

switch (option)
{
case 1:
{
string fileName;
cout << "Enter the name of the file including the path" << endl;
getline(cin, fileName);
break;
}
case 2:
cout << "You chose option 2";
break;
case 3:
cout << "You chose option 3";
break;
default:
cout << "value unknown";
}

return 0;
}

在用户输入 1 并且程序进入 switch...case 后,再次要求用户输入文件名。但是,这次程序不等待响应。

为什么 getline() 不能像在 switch...case 结构之外那样工作?

如有任何建议,我们将不胜感激。

最佳答案

cin在流中留下换行符 ( \n )。 cin.ignore()提取和丢弃字符。它可用于冲洗 cin直到 \n到达了。

因此,解决方案是添加 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); ,在第二次调用 getline(cin, fileName); 之前
同时添加 cin.clear()删除 cin 上的错误标志

示例:

case 1:
{
std::string fileName;
std::cout << "Enter the name of the file including the path" << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(std::cin, fileName);
break;
}

关于c++ - getline() 不等待 switch 内的输入...case (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19472612/

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