C++中getline被跳過


#include "stdafx.h"
#include"iostream"
#include"math.h"
#include"stdio.h"
#include"cstdlib"
#include"string"
#include"cstring"
using namespace std;
#define Max 20
struct player
{
	string name;
	char sex;
	int high;
};


int main(void)
{
	struct player bit[3];
	int i;
	cout << "press enter to start:";
	for (i = 0; i<3; i++)
	{
		cin.get();

		cout << "************player " << i << "***************" << endl;
		cout << "now input player " << i << "'s  name:";
		
		getline(cin, bit[i].name);
		cout << "now input player " << i << "'s  sex:";
		cin >> bit[i].sex;
		cout << "now input player " << i << "'s  high:";
		cin >> bit[i].high;
		
	}
	cout << "##################################################" << endl;
	for (i = 0; i<3; i++)
	{
		cout << "player " << i << "'s name is" << bit[i].name << "and his sex is" << bit[i].sex << "and the high is" << bit[i].high << endl;
	}
}

  上述代碼第一個循環里,i=0執行正常,i=1的時候就會跳過輸入名字這一項,直接到性別那里,如果i初值為1,則2的時候也跳過。

百度得知是cin和getline區別的問題。

在你寫getline()函數之前,一定有使用過了回車了吧
不論你輸入的是字符,數字或是回車,空格符,getline()函數都接收
而cin>>這種輸入方式卻是忽略回車的,如果你在getline()之前cin的一個數,回車被cin忽略了,卻被getline函數接收了,感覺就是這條語句被跳過了
所以解決的辦法是在getline函數之前再使用getline一次,將輸入流里的回車符接收掉,后面就能正常輸入了

百度知道的答案http://zhidao.baidu.com/link?url=-67TNObP8QxnE7tROIXviIDcS1SPWA7t5GzBcLV5yxu8sRfVS8W_H-0VR-HPW-ACbPAalWdFTfBGk3B5fnYqrq


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM