2.修改程序清单9.9,用string对象代替字符数组。这样,该程序将不再需要检查输入的字符串是否过长,同时可以将输入字符串同字符串""进行比较,以判断是否为空行。
#include <iostream>
using namespace std;
void strcount ( const string str )
{
static int total = 0;
int count = 0, i = 0;
cout << "\"" << str << "\" contains ";
while ( str[i] )
{
if ( str[i] == ' ' )
i++;
else
{
count++;
i++;
}
}
total += count;
cout << count << " characters" << endl;
cout << total << " characters total" << endl;
}
int main()
{
string str;
cout << "Enter a line:\n";
while ( getline ( cin, str ) )
{
if ( str == "" ) break;
strcount ( str );
cout << "Enter next line:\n";
}
cout << "Bye\n";
return 0;
}
3.下面是一个结构声明:
struct chaff
{
char dross[20];
int flag;
};
编写一个程序,使用定位new运算符将一个包含两个这样的结构的数组放在一个缓冲区中。然后,给结构的成员赋值(对于char数组,使用函数strcpy()),并使用一个循环来显示内容。一种方法是像程序清单9.10那样将一个静态数组用作缓冲区;另一种方法是使用常规new运算符来分配缓冲区。
#include <iostream>
#include <cstring>
using namespace std;
const int ArSize = 100;
struct chaff
{
char dross[20];
int slag;
};
char buffer[ArSize];
int main()
{
chaff ch,*p1;
char *str=new char[ArSize];
while ( cin >> str >> ch.slag )
{
strcpy ( ch.dross, str );
p1=new(buffer) chaff;
*p1=ch;
cout << "dross : " << p1->dross << endl;
cout << "slag : " << p1->slag << endl;
}
delete []str;
return 0;
}