cin、cin.get()、cin.getline()区别 (C++ )

还可以参考:https://www.cnblogs.com/dj0325/p/8513356.html

cin、cin.get、cin.getline区别

char x[20];
cin>>x   /*使用空白(空格、制表符和换行符)来确定字符串的位置,在输入完毕后,自动在结尾添加空字符*/

char x[20];
cin.getline(x,20)  /* 每次读取一行,通过换行符来确定行位,但不保存换行符*/     
/*cin.getline()和cin.get()都读取一行输入,直到换行符,但是随后cin.getline()丢弃换行符,cin.get()保留换行符在输入队列*/

char x[20];
cin.get(x);    /*读取到行尾,但是get保留换行符*/

以如下代码为例:

cin.getline(name,10)
cin.getline(dessert,10) /*这样写是可行的*/

cin.get(name); cin.get(dessert); /*第一次调用后换行符保留在输入队列,因此第二次调用时看到的第一个字符是换行符,因此get()认为是行尾,所以不会显示dessert变量的输入*/ /*修改如下*/ cin.get(name); cin.get(); /*用于处理上一条产生的换行符*/ cin.get(dessert); /*或者修改如下*/ cin.get(name).get(); /*就是将上面的一、二条合并*/ cin.get(dessert);

另一个例子:

#include <iostream>
using namespace std;
int main()
{

    cout << "what year was your house built ? \n";
    int year;
    cin >> year;
    cout << "what is its street address?";
    char address[80];
    cin.get(address, 80);
    cout << "yaer的值是" << year << endl;
    cout << "address的值是" << address << endl;
    cout << "Done!\n";
    return 0;

}

上面的代码不会显示address的输入,因此需要在  cin>>year  后加上  cin.get() ,从而使address能显示输入。

 另一个例子:

#include <iostream>         //程序的作用在于监测输入数组的部分的是否为数字
using namespace std;
const int Size=5;
int main()
{
int a[5];
for (int i=0;i<5;i++)
{ 
while(!(cin>>a[i]))         //数字判断
{
cin.clear();               //重置输入
while (cin.get() != '\n')      //用于读取行尾之前的所有输入,从而删除这一行的错误输入.
    continue;
cout<<"请重新输入"<<endl;
}
}
cout<<"输入结果为"<<a[0]<<a[1]<<a[2]<<a[3]<<a[4]<<endl;
}

猜你喜欢

转载自www.cnblogs.com/xiaochouk/p/8934382.html