在学习C/C++过程中对字符串的输入问题做一个总结,方便以后查阅。
1.用scanf读入字符串(注意数组越界问题)
- 用scanf可以将字符串读入字符数组;
- scanf会自动添加结尾的‘\0’;
- scanf读入到空格为止;
char line[100];
scanf("%s", line);//注意,不是&line
printf("%s", line);
Sylar 2016↙
Sylar
2.用cin输入字符串(与scanf相同)
3.使用cin.getline(char buf[], int bufSize)读入一行字符串
- 行长度不超过bufSize-1;
- 自动添加'\0';
- 回车换行符不会写入buf,但是会从输入流中去掉;
char line[10];
cin.getline(line, sizeof(line));
//或cin.getline(line,10);读入最多9个字符到line
cout << line;
A b c ↙ A b c1234567 ↙
A b c A b c1234
4.使用gets(char buf[])读入字符串(注意数组越界问题)
- 读入一行,自动添加'\0';
- 回车换行符不会写入buf,但是会从输入流中去掉;
char line[10];
gets(line);
//读入最多9个字符到line
cout << line;
A b c ↙A b c
5.使用getline(cin, line, 'z')读入字符串
- getline属于string类字符读取函数;
- 第三个参数可以不写,默认'\0',可以利用设置截止字符(第三个参数),读取多行在截止字符不输出;
- 识别空格和换行;
string line;
getline(cin, line, 'z');
//设置字符'z'为截止字符;
cout << line;
参考MOOC《程序设计与算法》课件a b c ↙x y z ↙a b cx y