C ++ iostream:使用cin>> var和getline(cin,var)输入错误 [英] C++ iostream: Using cin >> var and getline(cin, var) input errors
问题描述
我在C ++中创建一个简单的控制台应用程序,从用户获取字符串和字符输入。为了简单起见,我想使用字符串和字符数据类型将输入从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);
要获取char输入,我使用 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 ,而不必使用忽略,或者我可以调用以确保我的第一个字符不被跳过的方法
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);
}
推荐答案
>> var;
只从缓冲区抓取 var
保留缓冲区中的 \\\
,然后立即被
getline
only grabs the var
from the buffer, it leaves the \n
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 '\n'
getline(cin, var);
根据您的修改帖子
您不必使用 cin.ignore(); 代表
geline
从缓冲区中提取字符并将它们存储到 firstName
或( lastName
),直到分隔符为-newline('\\\
)。
'
This extracts characters from buffer and stores them into firstName
or (lastName
) until the delimitation character here -newline ('\n'
).
这篇关于C ++ iostream:使用cin>> var和getline(cin,var)输入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!