为什么在 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 ('
'
).
相关文章