C++字符串的输入问题

#include <IOSTREAM>
#include <MALLOC.H>
using namespace std;
/*字符串的输入:使用字符串输入的专属函数gets()、cin.get():
gets()同cin、scanf一样,无法检测数组下标越界的问题,这会导致程序运行时崩溃。
cin.get()可以指定录入的个数,从而避免了下标越界带来的问题。*/
void main()
{
	const int n = 100;
	char str[n] = {0};
	puts("请输入字符串:");//puts()也可直接输出字符串
	gets(str);
	cout<<str<<endl;

	char * p = (char *)malloc(n*sizeof(char));//申请动态堆区空间
	puts("请再输入字符串:");
	gets(p);
	puts(p);//puts()会自动输出字符串,并且遇到'\0'则输出换行。

	char str1[10] = {0};//定义一个长度为10的字符数组并初始化为0.
	puts("请再输入字符串:");
	cin.get(str1,10);//实际录入的为9个字符,最后一个被录为'\0',第三个参数不写,默认录入结束符为换行符.
	puts(str1);

}
/*
请输入字符串:
I love you C++ 知道么?
I love you C++ 知道么?
请再输入字符串:
Do you love me too?
Do you love me too?
请再输入字符串:
1234567890abcdefg
123456789
Press any key to continue
*/

你可能感兴趣的:(C++字符串的输入问题)