[問題] 文件寫入問題

看板C_and_CPP作者時間8年前 (2015/12/21 19:56), 8年前編輯推噓5(508)
留言13則, 4人參與, 最新討論串1/1
我要寫入一個文件檔,鍵盤輸入 姓名 電話 Email 如下: #include<iostream> #include<fstream> #include<string> using namespace std; int main() { ofstream myFile; int n = 0; char str1[50]; char str2[50]; myFile.open("Ex15_1.dat",ios::out) cout << "請輸入姓名、電話、Email地址" << endl; while(1) { cin >> str1 >> n >> str2; if (!strlen(str1) ==0) //若字串長度不等於0 { myFile << str1 << '\t' << n << '\t' << str2 << endl; } else break; } myFile.close(); return 0; } 結果按Enter不會中斷這個迴圈而且會一直複製 例如 我輸入 police 110 gmail hospital 119 hotmail 文件檔會是最後一行輸入的一直複製 police 110 gmail hospital 119 hotmail hospital 119 hotmail hospital 119 hotmail hospital 119 hotmail hospital 119 hotmail hospital 119 hotmail hospital 119 hotmail hospital 119 hotmail ..... 想了很久,不知道要怎麼修正,求解 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 175.180.106.216 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1450698967.A.76D.html

12/21 20:11, , 1F
(!strlen(str1) ==0) 這裡有問題
12/21 20:11, 1F

12/21 20:18, , 2F
因為我想用Enter結束,不就是str1字串長度==0時break嗎?
12/21 20:18, 2F

12/21 20:22, , 3F
在cin後,會一直重複迴圈,沒有輸入就會一直重複
12/21 20:22, 3F

12/21 20:28, , 4F
對,但沒有輸入就按Enter不就是字串長度=0?怎麼沒中斷QQ
12/21 20:28, 4F

12/21 20:29, , 5F
例如我輸入了兩行資料第三行不輸入了,直接按Enter想離開
12/21 20:29, 5F

12/21 20:31, , 6F
if中再加一行ZeroMemory(str1,50);
12/21 20:31, 6F

12/21 20:32, , 7F
cin如果直接按enter,不會把字串變成空的樣子
12/21 20:32, 7F

12/21 20:32, , 8F
你可以在while內第一行加上cout << "test";
12/21 20:32, 8F

12/21 20:33, , 9F
然後開啟程式直接按enter,會發現進不去while
12/21 20:33, 9F

12/21 20:33, , 10F
因為一直停留在前一行的cin
12/21 20:33, 10F

12/21 20:34, , 11F
另外你的if內也沒有改變str1的值,他就會變成在
12/21 20:34, 11F

12/21 20:35, , 12F
while內無窮迴圈,不會跳出
12/21 20:35, 12F
是的謝謝!!所以有方法可解嗎? 我試過用getline cin.getline(str1,80); cin.getline(str2,80); 這樣就可以用Enter讀取空字串,但是輸入就只能以換行來存入str1和str2了.. police gmail hospital hotmail 這樣.... 如果再getline(str1,80,' '); //這樣就不能以Enter來中斷.. 而且中間又必須輸入電話 int n 這樣不知道怎麼加..因為這只能用 cin >> n 這樣下一行的getline(str2,80); 就會抓到空白(因為抓完n後就回停留在換行符號前) ※ 編輯: akka5678 (175.180.106.216), 12/21/2015 21:31:32

12/21 21:47, , 13F
stringstream 可以解決你的問題
12/21 21:47, 13F
文章代碼(AID): #1MT-ZNTj (C_and_CPP)