0

Possible Duplicate:
Program is skipping over Getline() without taking user input

Alright, so I have a program that is running and at the start it prompts you for the data fill the data members. The program does this for 3 different objects.

My problem is that, at run time, after inputting data for the fist object the program proceeds to skip input for the second name and goes straight to the next option. It does the same thing for the third option's name. It also does this when you get the chance to change the data.

"Enter CD Name: Microsoft Word

1-Game

2-Word

3-Compiler

4-Spreadsheet

5-Dbase

6-Presentation

Enter the number that corresponds with the CD's Type: 2

Input CD Cost: 15.23

Enter CD Name: 1-Game <- ((Skips the input part and takes you directly to the menu!))

2-Word

3-Compiler

4-Spreadsheet

5-Dbase

6-Presentation

Enter the number that corresponds with the CD's Type:"

The issue is most likely in my member function, but I'm not sure what the issue is.

Here's my member function code:

void CDX::LoadInfo() //Prompts, validates and sets data members
{
cout << "Enter CD Name: ";
getline(cin, Name);

int choice=0;
do
{   cout << "1-Game\n2-Word\n3-Compiler\n4-Spreadsheet\n5-Dbase\n6-Presentation" << endl;
    cout << "Enter the number that corresponds with the CD's Type: ";
    cin >> choice;
} while ((choice <1)||(choice>6));

switch(choice)
//Code for case-switch statement goes here)

So what am I missing? Is this a buffer issue or am I prematurely ending the code in some way that causes it to skip?

4

3 回答 3

1

当发现无法转换的字符时,数字的转换将停止。在这种情况下,字符是 '\n'

当你使用getline读取一行时,这个字符被读取并丢弃,但是当你读取一个数字时,它被读取(知道数字是否继续),如果它不是数字的一部分,它被留在下一次读取的缓冲区。

例子:如果你写:“29312”并按下回车,你的缓冲区将被“29312\n”填充。

如果您使用 cin >> number 来读取标准输入,它将消耗数字,但会在缓冲区中留下“\n”。下次调用 getline 时,它​​将读取缓冲区中留下的空行。

于 2012-10-26T18:27:24.367 回答
0

我认为这是因为第一个'getline(cin,Name)'吞噬了最后一个换行键。当您输入成本并按 ENTER 时,呼叫getline完成。

您可以在收取费用后保留额外getline费用,以便消耗换行符。然后,我认为它会正确运行。

于 2012-10-26T18:23:18.460 回答
0

您已阅读“CD 成本”,但换行符仍保留在输入缓冲区中。在读取 CD 名称之前跳过空格:

ws(cin);
于 2012-10-26T18:23:20.220 回答