Why doesn#39;t getline(cin, var) after cin.ignore() read the first character of the string?(为什么在 cin.ignore() 之后没有 getline(cin, var) 读取字符串的第一个字符?)
问题描述
我正在用 C++ 创建一个简单的控制台应用程序,它从用户那里获取字符串和字符输入.为简单起见,我想使用 string 和 char 数据类型将输入从 cin 传递到.
I'm creating a simple console application in C++ that gets string and char inputs from the user. To make things simple, I would like to use the string and char data types to pass input from cin to.
为了获取字符串输入,我使用了 getline 方法:
To get string inputs, I'm using the getline method:
string var;
cin.ignore(); //I used ignore() because it prevents skipping a line after using cin >> var
getline(cin, var);
为了获得字符输入,我使用了 cin >> var 方法:
To get char inputs, I'm using the cin >> var method:
char var;
cin >> var;
这在大多数情况下都可以正常工作.但是,当我使用 getline 输入字符串时,它会忽略字符串的第一个字符.
This works fine for the most part. However, when I enter a string using getline, it ignores the first character of my string.
是否可以使用 getline 和 cin >> 而不必使用 ignore,或者我可以调用的方法来确保我的没有跳过第一个字符?
Is it possible to use getline and cin >> without having to use ignore, or a method I can call to ensure that my first character isn't skipped?
这是我同时使用 getline 和 cin >> 的完整代码示例:
This is a full sample of code where I use both getline and cin >>:
string firstName;
string lastName;
char gender = 'A';
cout << "First Name: ";
cin.ignore();
getline(cin, firstName);
cout << "Last Name: ";
cin.ignore();
getline(cin, lastName);
while(genderChar != 'M' && genderChar != 'F')
{
cout << "Gender (M/F): ";
cin >> genderChar;
genderChar = toupper(genderChar);
}
推荐答案
cin>>var;
只从缓冲区中获取var,而将
留在缓冲区中,然后立即被 getline
only grabs the var from the buffer, it leaves the
in the buffer,
which is then immediately grabbed up by the getline
所以,下面就好了,(如果我理解正确的话)
So, following is just fine, (if I understood correctly your problem)
cin>>var;
cin.ignore(); //Skip trailing '
'
getline(cin, var);
根据您的编辑帖子
你不必为 geline 使用 cin.ignore();
这从缓冲区中提取字符并将它们存储到 firstName 或 (lastName) 直到这里的分隔符 -newline ('
').
This extracts characters from buffer and stores them into firstName or (lastName) until the delimitation character here -newline ('
').
这篇关于为什么在 cin.ignore() 之后没有 getline(cin, var) 读取字符串的第一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在 cin.ignore() 之后没有 getline(cin, var) 读取字符串的第一个字符?
基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
