C++笔记:习题4.31

Exercise 4.31: Write a program that reads a string into a character array from the standard input. Describe how your program handles varying size inputs. Test your program by giving it a string of data that is longer than the array size you’ve allocated.

/* C++ Primer 习题 4.31
 * By Ceeji
 */

#include <iostream>
 
using namespace std;
 
const int cachelen = 5;
 
int main()
{
	char value;
	char sz [cachelen];
	char * sz_p = sz;
	int len = 0, maxlen = cachelen;
	bool added = false;
 
	while (cin >> value)
	{
		len++;
		if (len <= maxlen - 1)
		{
			*(sz_p + len - 1) = value;
		}
		else
		{
			char * sz_p2 = new char [len + cachelen];
			for (int i = 0; i < len - 1; i++)
			{
				*(sz_p2 + i) = *(sz_p + i);
			}
			*(sz_p2 + len - 1) = value;
			maxlen = len + cachelen;
			if (added)
			   delete [] sz_p;
			sz_p = sz_p2;
			added = true;
		}
	}
	*(sz_p + len) = NULL;
	cout << sz_p;
}

本文版权遵循 CC BY-NC-SA 4.0发布,转载需附带本文链接。

当前页阅读量为: