cin、cin.getline(arr, size)、getline(cin, str)
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
一、cin使用空白空格、制表符、换行符来确定字符串的截止位置
注意下方这段代码 使用cin来接收姓名和甜点名当我的名字长度大于一个单词长度时cin直接按空格进行接收将我输入的xiao接收到name中wei接收到dessert中导致我还没有输入dessert结果就全部打印了。
无法接受一整行内容
#include<iostream>
using namespace std;
int main()
{
const int Size = 20;
char dessert[Size];
char name[Size];
cout<<"Enter youer name"<<endl;
cin>>name;
cout<<"Enter your favourite dessert"<<endl;
cin>>dessert;
cout<<"I have some delicious "<<dessert;
cout<<" for you,"<<name<<".\n";
return 0;
}
二、面向行的输入 使用cin.getline(name, size)来接收
cin.getline第一个参数为接收字符串的字符数组名第二个参数为要读取的字符数
cout<<"Enter youer name"<<endl;
cin.getline(name, Size);
cout<<"Enter your favourite dessert"<<endl;
cin.getline(dessert, Size);
三、c++中string类使用getline()接收
也可以正常按行输出的目的
#include<iostream>
using namespace std;
#include<string>int main()
{
string name;
string dessert;
cout<<"Enter youer name"<<endl;
getline(cin, name);
cout<<"Enter your favourite dessert"<<endl;
getline(cin, dessert);
cout<<"I have some delicious "<<dessert;
cout<<" for you,"<<name<<".\n";
return 0;
}