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();};即可
相关文章推荐
- c++ 父类指针转换为子类指针后调用子类的成员函数问题
- Gvim自动编译运行c++11的程序
- C++中的std详解
- 忙里偷闲( ˇˍˇ )闲里偷学【C语言篇】——(4)for == while ?
- 忙里偷闲( ˇˍˇ )闲里偷学【C语言篇】——(4)for == while ?
- C++ Primer笔记(二)标准库类型
- C++ Primer笔记(一)变量和基本类型
- c语言的函数内存分配及指针函数的用法
- Effective C++——》条款25:考虑写一个不抛出异常的swap函数
- 【面试题004】c/c++字符串,替换空格
- 关于前置声明与C++中头文件相互包含的几点问题
- 忙里偷闲( ˇˍˇ )闲里偷学【C语言篇】——(3)输入输出函数
- 忙里偷闲( ˇˍˇ )闲里偷学【C语言篇】——(3)输入输出函数
- C语言进阶(牟海军)C 语言指针理解 续(2)
- Effective C++——》条款24:若所有参数皆需类型转化,请谓词函数采用non-member函数
- C语言中sscanf的用法
- Effective C++——》条款23:宁以non-member、non-frined替换member函数
- 钥匙计数之二
- C++随记:【cstdio(25) : error C2143: syntax error : missing '{' before ':'】
- C/C++语言void及void指针深层探索