面向行的输入

字符串的这个东西呢,还是挺麻烦的。
由于cin使用空白来定字符串的界,这意味着cin在获取字符数组输入时只读取一个单词。这就会造成程序的一些错误
比如下面这个程序

using namespace std;
int main()
{
    const int ArSize=20;
    char name[ArSize];
    char dessert[ArSize];
    cout<<"Enter your name:\n";
    cin>>name;
    cout<<"Enter your favorite dessert:\n";
    cin>>dessert;
    cout<<"I have some delicious"<<dessert;
    cout<<"for you,"<<name<<".\n";
    return 0;
}

我还没有对“输入甜点的提示”做出反应,程序就把他显示出来,而且立即显示最后一行了;
对于这些问题,我们就需要运用一些cin的较高级一些的特性——面向行的输入
1)getline()
调用方法:cin.getline(输入行数组的名称,读取的字符数);
这时候要注意的是如果读取的字符数这个参数定为20,则函数最多读取19个字符;getline()成员函数在读取指定数目字符或遇到换行符时停止读取;
所以我们可以把上面的程序改成这个样子

#include<iostream>
using namespace std;
int main()
{
    const int ArSize=20;
    char name[ArSize];
    char dessert[ArSize];
    cout<<"Enter your name:\n";
    cin.getline(name,ArSize);
    cout<<"Enter your favorite dessert:\n";
    cin.getline(dessert,ArSize);
    cout<<"I have some delicious"<<dessert;
    cout<<"for you,"<<name<<".\n";
    return 0;
}

这个程序就是符合我们要求的
2)get()

猜你喜欢

转载自www.cnblogs.com/Nicholastwo/p/9022328.html