7.2 字符串2(scanf、cin、cin.getline()、gets() )

scanf和cin一样,读入空格就停止读入了

#include<cstdio>
int main()
{
	char line[100];
	scanf("%s", line);//不用&line,因为字符串变量名就相当于地址
	printf("%s", line);
	return 0; 
} 

#include<iostream>
using namespace std;
int main()
{
	char line[100];
	cin >> line;
	cout << line << endl;
	return 0;
} 

#include<iostream>
using namespace std;
char line[10];
int main()
{
	cin.getline(line, sizeof(line));
	cout << line;
	return 0;
} 

cin.getline()相当于一个函数。

cin.geline() 最好不要和scanf一起使用,如果要用scanf,可以使用下面的gets()函数。

#include<iostream>
using namespace std;
char s[10];
int main()
{
	while(gets(s))
	{
		printf("%s\n", s);
	}
	return 0;
} 

由于gets()不知道数组的长度,读入什么装什么,很容易导致数组越界,导致后面的程序出错,所以要保证定义的字符数组足够大才行。

猜你喜欢

转载自blog.csdn.net/yanyanwenmeng/article/details/81090251