引言:
在刷题过程中,字符串的输入是十分恶心人的,本文着重总结getline,cin.getline,scanf,cin的区别,是否读入空格,结束标识符。用string类型和char[]类型做测试
正文
getline 读入字符串,cin.getline读入字符数组
用getline(cin,name)读入字符串,用cin.getline(place,256)读入字符数组
总结:getline与cin.getline 2种都会 读入空格,并且以回车为结束标志符
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string name;
char place[256];
//读入字符串
cout << "Please, enter your full name: ";
getline (cin,name);
cout << "Hello, " << name << "!\n";
cout<<endl<<endl;
//读入数组
cout << "Please, enter your full name: ";
cin.getline(place,256);
cout<<place<<" welcome you !"<<endl;
return 0;
}
scanf与cin
总结:scanf不能读入string类型,cin可以读入string与字符数组。并且scanf与cin都不读入空格,cin与scanf以空格作为判断符
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string name;
char place[256];
//读入字符串
cout << "Please, enter your full name: ";
// scanf("%s",name);错误 不用用scanf读入字符串
cout << "Hello, " << name << "!\n";
cout<<endl<<endl;
//读入数组
cout << "Please, enter your full name: ";
// cin.getline(place,256);
scanf("%s",place);
cout<<place<<" welcome you !"<<endl;
return 0;
}
gets在c++14中已经被移除,并且容易出现bug,不推荐使用,所以此处讨论