C++primer plus第六版课后编程题答案9.1

golf.h
#ifndef GOLF_H_ 
#define GOLF_H_

const int Len=40;
struct golf{
       char fullname[Len];
       int handicap;
       };
void setgolf(golf &g,const char *name,int hc);
int setgolf(golf &g);
void handicap(golf &g,int hc);
void showgolf(const golf &g);

#endif
golf.cpp
#include <iostream>
#include "golf.h";
#include <string>
using namespace std;
void setgolf(golf &g,const char *name,int hc)
{
	//g.fullname=name;	//不能直接赋值,为什么呢?因为字符数组不能直接赋值
	strcpy(g.fullname,name);
	g.handicap=hc;
}
int setgolf(golf &g)
{
	cout<<"Please enter the name:";
	cin.getline(g.fullname,Len);//cin.getline将丢弃换行符
	if(g.fullname[0]=='')
		return 0;
	cout<<"
g.fullname="<<g.fullname<<endl;
	cout<<"Please enter the hc:";
	//cin.clear();//这里不需要清除输入流,因为此时输入流已经为空
	while(!(cin>>g.handicap)){//由于!优先级比>>高,所以要加()
		//while(cin.get()=='
')//吸收掉输入的回车符,否则会一直执行下面的语句
		//{	发现如果输入错误的类型,还是会一直出错
		//	cin.clear();//清除错误输入,
			cin.sync();
			//cin.clear();
			//cin>>g.handicap;
			cin.get();
			cout<<"
Please enter the hc1:";
			//continue;
		//}
	};/*
	  这段语句如果输入的是一个string类型,即几个字符,就会一直执行while里面的循环,我已经清空了输入流啊,不是应该等待下一次输入么,这是为什么呢?
错在哪里了,应该怎么改呢? 
	  */ 


	//while(cin.get()!='
')	//倘若不去掉其他的字符,例如回车符,可能会导致下一次输入为空
		///continue;
		cout<<"hc="<<g.handicap<<endl;
		cin.sync();//最后要清除一次输入流,否则可能残存的输入流进入下一cin中
		return 1;
}
void handicap(golf &g,int hc)
{
	g.handicap=hc;
}
void showgolf(const golf &g)
{
	cout<<"
show !"<<endl;
	cout<<"g.fullname:"<<g.fullname<<endl;
	cout<<"g.handicap:"<<g.handicap<<endl;
}

main91.cpp

#include <iostream>
#include "golf.h"
using namespace std;

void main91()
{
	golf arr[3];
	for(int i=0;i<3;i++)
	{
		int flag=setgolf(arr[i]);
		if(flag)
			showgolf(arr[i]);
		else 
			break;
	}

	system("pause");
}
问题已经解决:
改为while(!(cin>>g.handicap))
{
	cin.clear();
	cin.get();
};
即可












原文地址:https://www.cnblogs.com/qq84435/p/3664862.html