[問題] string、char、getline

看板C_and_CPP作者 (被找麻煩了...)時間13年前 (2010/10/31 15:50), 編輯推噓2(202)
留言4則, 3人參與, 最新討論串1/1
遇到的問題: (題意請描述清楚) 請問如果輸入是William W,因為中間有空格,所以用cin.getline來讀取 但是getline是讀入陣列,請問原始宣告是用string的話,該怎麼在cin輸入 時,讀入整行內容呢? 附上我的程式碼: #include<iostream> #include<string> using namespace std; int main() { string name; string dessert; cout << "Enter your name: "; cin.getline(name,20);//這邊的name因為不是char,所以編譯不過 cout << "Enter your favorite dessert: "; cin >> dessert; cout << "I have some delicious " << dessert; cout << " for you, " << name << ".\n"; system("PAUSE"); } 希望得到的正確結果: 希望輸入Will Wi這樣的name可以完整存入name中 程式跑出來的錯誤結果: 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) Dev-C++ 有問題的code: (請善用置底文標色功能) 補充說明: -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 125.227.94.121 ※ 編輯: silia 來自: 125.227.94.121 (10/31 15:50)

10/31 15:54, , 1F
getline(cin, name);
10/31 15:54, 1F

10/31 15:55, , 2F
哇!我會了!謝謝樓上^^
10/31 15:55, 2F

10/31 16:13, , 3F
想到用 &s[ 0 ] 丟給 getline... XD 後果自負
10/31 16:13, 3F

10/31 16:17, , 4F
不好吧 標準沒有規定string的實作方式耶
10/31 16:17, 4F
文章代碼(AID): #1CpH_76R (C_and_CPP)