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
#include “golf.h”;
#include
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
#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.royalchen.com/ author:royalchen Email:royalchen@royalchen.com ———————————————————————————————————————————————————
// <![CDATA[ var fileName = ‘23518117’; var commentscount = 3; var islock = false // ]]> // <![CDATA[ $(function () { $(“#ad_frm_0”).height(“90px”); setTimeout(function(){ $(“#ad_frm_2”).height(“200px”); },1000); }); // ]]>
// <![CDATA[ $(function(){ setTimeout(function(){ $.get(“/guang_jing/svc/GetTagContent”,function(data){ $(“.tag_list”).html(data).show(); }); }); },500); // ]]>
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2016/02/24/cprimerplus第六版课后编程题答案91/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!