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;
}

题外话:我帮你整理了包括 AI 写作、绘画、视频(自媒体制作)零门槛 AI 课程 + 国内可直接顺畅使用的软件。想让自己快速用上 AI 工具来降本增效,辅助工作和生活?限时报名

当前页阅读量为: