C/C++输入输出流
istream中的類(如cin)提供了一些面向行的類成員函數:getline()和get()。這兩個函數都讀取一行輸入,直到達到換行符。不同的是,getline()將丟棄換行符,而get()將換行符保留在輸入序列中。
目錄
一、字符串 I/O
二、string類 I/O
一、字符串 I/O
1.面向行的輸入:getline()
getline()函數讀取整行,它使用通過回車鍵輸入的換行符來確定輸入結尾。要調用這種方法,可以使用cin.getline()。該函數有兩個參數,第一個參數是用來存儲輸入行的數組的名稱,第二個參數是要讀取的字符數。
ex:cin.getline(typename,size).
#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()
get()與getline()接受的參數相同,解釋參數的方式也相同,并且都讀取到行尾。但并不再讀取并丟棄換行符,而是將其留在輸入隊列中。
ex:cin.get(typename,size).
當第一次調用后,換行符留在輸入隊列中,因此第二次調用時看到的第一個字符便是換行符。因此get()認為已經到達行尾,而沒有發現任何可讀取的內容。
此時可借用get()的另一種變體,使用不帶任何參數的cin.get()調用可讀取下一個字符(即使是換行符)。
因此可以用它來處理換行符,為讀取下一行輸入做好準備。
ex:
cin.get(typename,size);
cin.get();
cin.get(typename,size);
另一種使用get()的方式是將兩個類成員函數拼接起來:
cin.get(typename,size).get();
#include <iostream> using namespace std; int main() {const int ArSize = 20;char name[ArSize];char dessert[ArSize];cout << "Enter your name:\n";cin.get(name,ArSize).get();cout << "Enter your favorite dessert:\n";cin.get(dessert,ArSize).get();cout << "I have some delicious " << dessert;cout << " for you , " << name << ".\n"; return 0; }二、string類 I/O
1.使用string對象的方式與使用字符數組相同
- 可以使用C-風格字符串來初始化string對象。
- 可以使用cin來將鍵盤輸入存儲到string對象。
- 可以使用cout來顯示string對象。
- 可以使用數組表示法來訪問存儲在string對象中的字符。
2.get(cin,str)方法?
#include<iostream> #include<cstring> using namespace std; //字符數組i/o int main() {char charr1[20];char charr2[20];cout << "Enter your first name:\n";cin.get(charr1,20).get();cout << "Enter your last name:\n";cin.get(charr2,20).get();strcat(charr1,charr2);cout << "Here's the information in a single string :\n";cout << charr1;return 0; } //string類i/o int main() {string str1,str2;cout << "Enter your first name:";getline(cin,str1);cout << "Enter your first name:";getline(cin,str2);cout << "Here's the information in a single string :";cout << str1 << " , " << str2;cout << "\n";string str3;cout << "Enter third name:";cin >>str3;cout << "str3 = " << str3;return 0; }3.string類的其他操作
-
可以使用函數strcpy()將字符串復制到字符數組中。
-
可以使用函數strcat()將字符串附加到字符數組末尾。
ex:? ?strcpy(charr1,charr2)? ?strcat(charr1,charr2)
總結
以上是生活随笔為你收集整理的C/C++输入输出流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java GUI界面
- 下一篇: C++描述杭电OJ 2012.素数判定