[英]c++ why is there still input buffer left?
After my first entry, my second entery name
field fills up with the input buffer from the previous entry. 在我的第一个输入项之后,我的第二个输入项name
字段将填充上一个输入项的输入缓冲区。 Why? 为什么? I am even using the getline
but the problem still persists. 我什至在使用getline
但问题仍然存在。 Please help me with the problem. 请帮我解决这个问题。 This is question from Jumping Into C++ book . 这是“ 跳入C ++”书中的问题。
#include <iostream>
#include <string>
using namespace std;
struct Person
{
string name;
string address;
long long int PhoneNumber;
};
void displayEntries(Person p[])
{
int enteryNumber;
cout << "Enter the entry number of the person for details(enter 0 to display all entries): ";
cin >> enteryNumber;
if(enteryNumber == 0)
{
for(int i = 0; i < 10; i++)
{
cout << "Entery Number: " << i + 1;
cout << "Name: " << p[i].name << endl;
cout << "Address: " << p[i].address << endl;
cout << "Phone Number: " << p[i].PhoneNumber << endl;
}
}
do
{
cout << "Entery Number: " << enteryNumber;
cout << "Name: " << p[enteryNumber].name << endl;
cout << "Address: " << p[enteryNumber].address << endl;
cout << "Phone Number: " << p[enteryNumber].PhoneNumber << endl;
} while (enteryNumber != 0);
}
int main()
{
Person p[10];
for(int i = 0; i < 10; i++)
{
cout << "Enter the details of the person\n\n";
cout << "Name: ";
getline(cin, p[i].name);
cout << "Address: ";
getline(cin, p[i].address);
cout << "Phone Number: ";
cin >> p[i].PhoneNumber;
cout << endl;
}
displayEntries(p);
return 0;
}
cin >> p[i].PhoneNumber;
only gets the number. 只得到号码。 That leaves the line ending still in the input buffer to be read the next time you try to read a line. 这样,在您下次尝试读取行时,仍将行结尾保留在输入缓冲区中。
You can see what is happening when you read the reference for getline : 阅读getline参考时,您可以看到发生了什么:
When used immediately after whitespace-delimited input, eg after 在空格分隔的输入之后立即使用时,例如在
int n;
std::cin >> n;
getline(cin, n); //if used here
getline
consumes the endline character left on the input stream by operator>>,
and returns immediately. getline
使用operator>>,
消耗输入流上剩余的结束operator>>,
并立即返回。 A common solution is to ignore all leftover characters on the line of input with 常见的解决方案是忽略输入行上的所有剩余字符
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
before switching to line-oriented input. 在切换到面向行的输入之前。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.