[問題] 用string讀取整個file的問題

看板C_and_CPP (C/C++)作者 (費諾)時間11年前 (2014/07/18 05:15), 11年前編輯推噓2(205)
留言7則, 3人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) visualstudio2013 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) #include<iostream> #include<fstream> #include<string> 問題(Question): 好像從檔案中讀出來的string沒有讀完,且也沒辦法做處理. 餵入的資料(Input): a a a a a a a 預期的正確結果(Expected Output): 7 錯誤結果(Wrong Output): 0 程式碼(Code):(請善用置底文網頁, 記得排版) int main() { infile.open("test1.txt"); if (infile.fail()) { cout << "The opening of the input file failed." << endl; } //check infile cout<<countblank(read_file(infile))<<endl; infile.close(); return 0; } string read_file(ifstream& infile) { string text; //For string of the file string temp; //For getting the string while (!infile.eof()) { getline(infile, temp); text.append(temp); } // To get the whole string from the file return text; // Return String text } int countblank(string article) { int counterblank = 0; string::iterator it; for (it = article.begin(); it != article.end(); it++) { if ((*it == ' ') || (*it == '\n')||(*it == '-')) { counterblank++; } } return counterblank; } 補充說明(Supplement): 我的第二個函式主要是要來讀取空白或是換行等等 我是拿以前的程式碼貼上去的 所以我想沒有甚麼問題 所以我想問題可能再讀取那邊 BTW 它除了沒有去數空白及換行的數目之外 讀出來的string也不讓我做大小寫轉換 -- 306 長官 , 恕我冒犯 ! 是標緻406 , 應該不是原廠的 白癡 我是說他的速度306 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.113.136.219 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1405631727.A.F47.html

07/18 15:32, , 1F
getline 讀進來的字串不含最後的換行, 所以你的 text 的內容
07/18 15:32, 1F

07/18 15:32, , 2F
將會是連續的七個 a
07/18 15:32, 2F

07/18 15:33, , 3F
因此 countblank 的結果自然是 0 了
07/18 15:33, 3F

07/18 15:36, , 4F
至於你的大小寫轉換是怎麼做的? 也貼一下程式吧
07/18 15:36, 4F
bool iscap(char c) { if ((c >= 'A') && (c <= 'Z')) { return true; } else { return false; } } char decap(char c) { if ((c >= 'A') && (c <= 'Z')) { return (c + ('a' - 'A')); } else { return c; } } string normalized(string article) { article = " " + article; string::iterator it; for (it = article.begin(); it != article.end(); it++) { if ((*it == '’') || (*it == ',') || (*it == '“') || (*it == '”') || (*it == '?') || (*it == '(') || (*it == ')') || (*it == '.')) { article.erase(it); } else if (iscap(*it)) { *it = decap(*it); } } return article; }

07/18 15:53, , 5F
提外話 通常用vector<char>來當容器會好一點
07/18 15:53, 5F

07/18 15:54, , 6F
可以免除依些binary要做的特殊處理問題
07/18 15:54, 6F

07/18 21:17, , 7F
我是不太愛用C-string 用個transform作處理其實也還ok
07/18 21:17, 7F
謝謝各位大大的寶貴意見 ※ 編輯: feanor (219.68.109.148), 07/19/2014 00:54:18 ※ 編輯: feanor (219.68.109.148), 07/19/2014 00:56:12
文章代碼(AID): #1Jo3plz7 (C_and_CPP)
文章代碼(AID): #1Jo3plz7 (C_and_CPP)