代码块
getline():
#include <iostream>
using namespace std;
int main()
{
char str1[30], str2[30];
cin.getline(str1, 30);
char a = cin.get(); //读取单个字符
cout << "good Time!";
cout << a;
return 0;
}
输入:
123
456
输出:
good Time!4
Press any key to continue.
而
get():
#include <iostream>
using namespace std;
int main()
{
char str1[30], str2[30];
cin.get(str1, 30);
char a = cin.get(); //读取单个字符
cout << "good Time!";
cout << a;
return 0;
}
输入为:
123
输出结果为:
123
good Time!
Press any key to continue
从这两段代码可以看出,getline()和get()都读取一行输入,
然而
getline将丢弃输入换行符,而get()将换行符保留在输入流中。
所以,第一段代码需要输入两次,即输入123,之后还得输入456,然而cin.get()只能得到一个字符,所以输出为good Time!4, 而第二段代码中的get(cin, 30)将换行符保留在输入流中,后一个get()即得到了这个换行符,因此在输出good Time!之后换行。