【C++】返回C-风格字符串的函数

假设你要编写一个返回字符串的函数。但是函数无法返回一个字符串,但是可以返回字符串的地址!这样效率更高!

函数接受两个参数:一个字符+一个数组

使用new创建一个长度与数组参数相等的字符串,然后将每个元素都初始化 为该字符,返回新字符串的指针

//返回C-风格字符串的函数
#include <iostream>
char * buildstr(char c, int n);
int main()
{
	using namespace std;
	int times;
	char ch;

	cout << "输入一个字符: ";
	cin >> ch;
	cout << "输入一个整数: ";
	cin >> times;
	char *ps = buildstr(ch, times);
	cout << ps << endl;
	delete [] ps;  //释放内存
	ps = buildstr('+', 20);
	cout << ps << "-Done-" << ps << endl;
	delete [] ps;

	cin.get();
	system("pause");
	return 0;

}

char * buildstr(char c, int n)
{
	char * pstr = new char[n + 1];
	pstr[n] = '\0';
	while (n-->0)
	{
		pstr[n] = c;
	}
	return pstr;
}

 

猜你喜欢

转载自blog.csdn.net/qq_15698613/article/details/85291316