C++ get()和getline()的区别

getling():每次读取一行输入的字符串时,它通过换行符(\n)来确定行尾,之后丢弃Enter生成的换行符,取而代之的是空字符。
get():每次读取一行输入的字符串时,它通过换行符(\n)来确定行尾,之后丢弃Enter生成的换行符,并保留换行符到队列中。
如果连续两次调用get():

#include <iostream>
using namespace std;
const int SIZE = 20;
int main(){

    char name[SIZE];
    char dessert[SIZE];

    cout << "Enter your name:";
    cin.get(name, SIZE);
    cout << "Enter your favorite dessert: ";
    cin.get(dessert, SIZE);
    cout << "I have some delicious " << dessert;
    cout << " for you," << name << ".\n";


    return 0;
}

输出结果:
Enter your name:zxw
Enter your favorite dessert::
I have some delicious for you,zxw

第二个get()保存着第一个get()保存的换行符,所有没有输入直接进入下一行。

解决方法:使用一个不带任何参数的cin.get()调用可读取下一个字符,因此通常用这种方法来处理换行符。
我们将上述程序改为
cin.get(name,ArSize);
cin.get();
cin.get(dessert,ArSize);

猜你喜欢

转载自blog.csdn.net/qq_43461641/article/details/89449622