• 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
  • 相关阅读:
    Vi与Vim
    Linux文件压缩、打包、备份
    Linux文件与目录操作
    Linux文件权限与目录
    Linux学习笔记
    Android——复制项目出现Application Installation Failed
    《鸟哥的Linux私房菜》学习笔记0——计算机概论
    Android——自定义多击事件
    《跟孩子学Python》
    《简明Python教程》读书笔记
  • 原文地址:https://www.cnblogs.com/wswang/p/4833900.html
Copyright © 2020-2023  润新知