8.设计一个描述鱼的结构声明。结构中应当包括品种、重量(整数,单位为盎司)和长度(英寸、包括小数)。
答:
struct fish
{
char kind[];
int weight;
float length;
};
12、
假设treacle是一个包含10个元素的float数组,请声明一个指向treacle的第一个元素的指针,并使用该指针来显示数组的第一个元素和最后一个元素。
答:
float *pf = treacle;
cout<<pf[0]<<" "<<pf[9]<<endl;
//或者
float *pf=&treacle[10];
cout<<*pf<<" "<<*(pf+9)<<endl;
13、编写一段代码,要求用户输入一个正整数,然后创建一个动态的int数组,其中包含的元素数目等于用户输入的值。首先使用new来完成这项任务,再使用vector对象来完成这项任务。
unsigned int n;
cout<<"Please enter an integer:"<<endl;
cin>>n;
int *pa=new int[n];
使用vector对象来完成这个任务:
#include<vector>
using namespace std;
unsigned int n;
cout<<"Please enter an integer: ";
cin>>n;
vector<int>vi(n);
15、
编写一段代码,给问题8中描述的结构动态分配内存,再读取该结构的成员的值。
struct fish
{
char kind[];
int weight;
float length;
};
fish *pa = new fish;
cout<<"Please enter kind of fish: ";
cin>>pa->kind;
cout<<"Please enter weight of fish: ";
cin>>pa->weight;
cout<<"Please enter lenght of fish: ";
cin>>pa->length;
或者
cin>>(*pa).kind;
cin>>(&pa).weight;
cin>>(*pa).length;
16.程序清单4.6指出了混合输入数字和一行字符串储存的问题。如果将下面代码:
cin.getline(address,80);
替换为
cin >> address;
将对程序的运行带来什么影响?
答:
先了解一下:
cin.getline():面向行的输入,读取整行,使用回车键输入的换行符来确定输入结尾,并丢弃换行符。
cin.get():面向行的输入,读取到行尾,不再读取换行符并且不丢弃换行符,二是将其留在输入队列中。
贴上4.6的例子:
#include<iostream>
int main()
{
using namespace std;
cout<<"What year was your house built?"<<endl;
int year;
cin>>year;
cout<<"What is its address?"<<endl;
char address[80];
cin.getline(address,80);
cout<<"Year built: "<<year<<endl;
cout<<"Address:"<<address<<endl;
return 0;
}
用户根本没有输入address 的机会。当cin 读取年份时,将回车键生成的换行符留在了输入队列中,而cin.getline()看到换行符后将认为这是一个空行,并将一个空字符串赋值给address数组。当采用cin>>address将使程序跳过空白,直到找到空白字符为止。
附加解决方法
cin>>year;
cin.get();//or cin.get(ch)
//(cin>>year).get();
17.声明一个vector对象和一个array对象,他们都包含10个string对象。指出所需的头文件,但不要使用using。使用const来指定要包含的string对象数。[cpp] view plain c
#include<vector>
const int num=10;
std::vector<std::string> vi(num);
std::string<std::string.num> str;