您的位置:首页 > 编程语言 > C语言/C++

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

2014-04-12 10:41 134 查看
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]=='\0')
return 0;
cout<<"\ng.fullname="<<g.fullname<<endl;
cout<<"Please enter the hc:";
//cin.clear();//这里不需要清除输入流,因为此时输入流已经为空
while(!(cin>>g.handicap)){//由于!优先级比>>高,所以要加()
//while(cin.get()=='\n')//吸收掉输入的回车符,否则会一直执行下面的语句
//{	发现如果输入错误的类型,还是会一直出错
//	cin.clear();//清除错误输入,
cin.sync();
//cin.clear();
//cin>>g.handicap;
cin.get();
cout<<"\nPlease enter the hc1:";
//continue;
//}
};/*
这段语句如果输入的是一个string类型,即几个字符,就会一直执行while里面的循环,我已经清空了输入流啊,不是应该等待下一次输入么,这是为什么呢?
错在哪里了,应该怎么改呢?
*/

//while(cin.get()!='\n')	//倘若不去掉其他的字符,例如回车符,可能会导致下一次输入为空
///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<<"\nshow !"<<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();};即可

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: