1.如何声明下述数据?
a.actor是由30个char组成的数组。 b.betsie是由100个short组成的数组。 c.chuck是由13个float组成的数组。 d.dipsea是由64个long double组成的数组。
char actor[30];
short betsie[100];
float chuck[13];
long double dipsea[64];
2.使用模板类array而不是数组来完成问题1。
#include"array.h"
using namespace std;
int main(){
array<char,30> actor;
array<short,100> betsie;
array<float,13> chuck;
array<long double,64> dipsea;
}
3.声明一个包含5个元素的int数组,并将它初始化为前5个正奇 数。
int odd[5]={1,3,5,7,9};
4.编写一条语句,将问题3中数组第一个元素和最后一个元素的和 赋给变量even。
int odd[5]={1,3,5,7,9};
int even=odd[0]+odd[4];
5.编写一条语句,显示float数组ideas中的第2个元素的值。
float ideas[3]={1,2,3};
std::cout<<ideas[1];
6.声明一个char的数组,并将其初始化为字符串“cheeseburger”。
char str_1[13]="cheeeseburger";
7.声明一个string对象,并将其初始化为字符串“Waldorf Salad”。
std::string s="Waldoef Salad";
8.设计一个描述鱼的结构声明。结构中应当包括品种、重量(整 数,单位为盎司)和长度(英寸,包括小数)。
struct fish
{
char name[20];
int weight;
float lenght;
}
9.声明一个问题8中定义的结构的变量,并对它进行初始化。
struct fish
{
char name[20];
int weight;
float lenght;
}
fish whale={"whale", 2000, 21.3};
10.用enum定义一个名为Response的类型,它包含Yes、No和 Maybe等枚举量,其中Yes的值为1,No为0,Maybe为2。
enum Response{ Yes, No, Maybe };
11.假设ted是一个double变量,请声明一个指向ted的指针,并使用 该指针来显示ted的值。
#include <iostream>
using namespace std;
int main() {
double ted=3.14;
double* pointer = &ted;
std::cout << "ted = " << ted
<< "using pointer: ted = " << *pointer;
return 0;
}
12.假设treacle是一个包含10个元素的float数组,请声明一个指向 treacle的第一个元素的指针,并使用该指针来显示数组的第一个元素和 最后一个元素。
#include <iostream>
using namespace std;
int main() {
float treacle[10] = { 1,2,3,4,5,6,7,8,9,0 };
float* ptr;
ptr = treacle;
std::cout << "treacle[0] = " << *ptr;
std::cout << " and treacle[9] = " << *(ptr + 9);
return 0;
}
13.编写一段代码,要求用户输入一个正整数,然后创建一个动态 的int数组,其中包含的元素数目等于用户输入的值。首先使用new来完 成这项任务,再使用vector对象来完成这项任务。
#include<vector>
#include<string>
#include <iostream>
using namespace std;
int main() {
int n;
cout << "please enter a integer: " << endl;
cin >> n;
int *pi = new int[n];
delete[] pi;
std::vector<int> vec1(n);
return 0;
}
14.下面的代码是否有效?如果有效,它将打印出什么结果?
打印出该字符串的第一个字符的地址
15.编写一段代码,给问题8中描述的结构动态分配内存,再读取 该结构的成员的值。
#include <iostream>
using namespace std;
int main() {
struct fish
{
char name[20];
int weight;
float lenght;
};
fish *f1 = new fish;
cout << "enter the name of fish: ";
cin >> f1->name;
cout << "enter the lenght of fish: ";
cin >> (*f1).lenght;
cout << "enter the weight of fish: ";
cin >> f1->weight;
cout << "name: " << f1->name << "\nlenght: " << f1->lenght << "\nweight: " << f1->weight;
delete f1;
return 0;
}
16.程序清单4.6指出了混合输入数字和一行字符串时存储的问 题。
如果将下面的代码:
cin.getline( address , 80 );
替换为:
cin >> address;
将对程序的运行带来什么影响?
1.cin会将空格、制表符和换行符作为结束标识,可能会提前结束读取。
2.cin读取完后会将换行符继续保留再输入序列中,会导致下一个读取读取到换行符而直接结束。
17.声明一个vector对象和一个array对象,它们都包含10个string对 象。指出所需的头文件,但不要使用using。使用const来指定要包含的 string对象数。
#include<vector>
#include<array>
#include<string>
#include <iostream>
//using namespace std;
int main() {
const int N = 10;
std::vector<std::string> vec(N);
std::array<std::string, N> arr;
return 0;
}