Exercise 4.31:
编写程序从标准输入设备读入字符串,并把该串存放在字 符数组中。描述你的程序如何处理可变长的输入。提供比 你分配的数组长度长的字符串数据测试你的程序。
string in_str;
const size_t str_size = ;
char result_size[str_size+]; cout<<"Enter a string<="<<str_size<<"characters"<<endl;
cin>>in_str; size_t len = strlen(in_str.c_str());
if(len > str_size)
{
len = str_size;
cout<<"String is longer than "<<str_size<<"characters and is stored only"<<str_size<<"characters"<<endl;
} strncpy(result_size,in_str.c_str(),len); result_size[len+] = '\0';
Exercise 4.32:
编写程序用 int 型数组初始化 vector 对象。
const size_t arr_size = ;
int int_arr[arr_size]; cout<<"Enter"<<arr_size<<"Numbers:"<<endl;
for(size_t ix =;ix != arr_size;++ix)
{
cin>>int_arr[ix];
}
vector<int> ivec(int_arr,int_arr+arr_size);
Exercise 4.33:
编写程序把 int 型 vector 复制给 int 型数组。
vector<int> ivec;
int ival; cout<<"Enter numbers:(Ctrl+z to end)"<<endl;
while(cin>>ival)
{
ivec.push_back(ival);
} int *parr = new int[ivec.size()];
size_t ix = ;
for(vector<int>::iterator iter = ivec.begin();iter != ivec.end();++iter,++ix)
{
parr[ix] = *iter;
}
delete [] parr;
Exercise 4.34:
编写程序读入一组 string 类型的数据,并将它们存储在 vector 中。接着,把该 vector 对象复制给一个字符指 针数组。为 vector 中的每个元素创建一个新的字符数 组,并把该 vector 元素的数据复制到相应的字符数组 中,后把指向该数组的指针插入字符指针数组。
Exercise 4.35:
输出习题 4.34 中建立的 vector 对象和数组的内容。输 出数组后,记得释放字符数组。
vector<string> svec;
string str; cout<<"Enter string:(Ctrl+z to end)"<<endl;
while(cin>>str)
svec.push_back(str); char **parr = new char*[svec.size()]; size_t ix = ;
for(vector<string>::iterator iter = svec.begin();iter != svec.end();++iter,++ix)
{
char *p = new char[(*iter).size()+];
strcpy(p,(*iter).c_str());
parr[ix] = p;
} //输出vector对象的内容
cout<<"Content of vector:"<<endl;
for(vector<string>::iterator iter2 = svec.begin();iter2 != svec.end();++iter2)
cout<<*iter2<<endl;
cout<<"Content of character arrays:"<<endl;
for(ix = ;ix != svec.size();++ix)
cout<<parr[ix]<<endl;
//释放各个字符数组
for(ix=;ix != svec.size();++ix)
delete [] parr;