#include <iostream>
using namespace std;
//標準輸入輸出:
/*
cin.get() //一次只能讀取一個字符
cin.get(一個參數) //讀一個字符
cin.get(兩個參數) //可以讀字符串
cin.getline()
cin.ignore()
cin.peek()
cin.putback()
*/
void test01()
{
//cin.get() //一次只能讀取一個字符
char c = cin.get();
cout << "c = " << c << endl;
c = cin.get();
cout << "c = " << c << endl;
c = cin.get();
cout << "c = " << c << endl;
c = cin.get();
cout << "c = " << c << endl;
}
//當輸入as時,此時緩衝區中的數據是:a,s,換行;打印出來的時:c=a,c=s,c=
//再輸入一個字符,最後的c= 才能顯示出來;
void test02()
{
//cin.get(兩個參數) //可以讀字符串
char buf[1024];
cin.get(buf, 1024);
cout << buf << endl;
//輸入Hello world 輸出 hello world;
}
void test03()
{
//cin.get(兩個參數) //可以讀字符串
char buf[1024];
cin.get(buf, 1024);
char c = cin.get();//如果cin.get(兩個參數)沒拿走換行符,則下面的不用第二次輸入就能自動執行;
if (c == '\n') {
cout << "換行還在緩衝區" << endl;
}
else {
cout << "換行不在緩衝區" << endl;
}
cout << buf << endl;
}
//test03的測試結果:cin.get讀取字符串時,不會把換行符拿走,遺留在緩衝區;
//cin.getline()
void test04()
{
char buf[1024];
cin.getline(buf, 1024);
//cin.getline()取走了換行符,且沒有輸出;
//所以下面的程序需要多一次的輸入才能執行;
char c = cin.get();
if (c == '\n') {
cout << "換行還在緩衝區" << endl;
}
else {
cout << "換行不在緩衝區" << endl;
}
}
//cin.ignore()
void test05()
{
cin.ignore();
char c = cin.get();
cout << "c= " << c << endl;
}
//輸入as,輸出s,因爲忽略了字符a;
//cin.ignore(n)表示忽略了n個字符;
//cin.peek() 頭盔
void test06()
{
char c = cin.peek();
cout << "c= " << c << endl;
c = cin.peek();
cout << "c= " << c << endl;
}
//輸入as,輸出c=a,c=a;
//輸入as,偷看一眼a,輸出a,然後放回緩衝區,緩衝區中還是as,再輸出a;
//cin.putback() 放回
void test07()
{
char c = cin.get();
cin.putback(c);
char buf[1024];
cin.getline(buf, 1024);
cout << buf << endl;
}
int main()
{
//test01();
//test02();
//test03();
//test04();
//test05();
test06();
test07();
system("pause");
return 0;
}