我遇到了這個程序的麻煩。該程序應該告訴用戶在給定輸入中有多少行,單詞,字符,唯一行和唯一字。到目前爲止,文字和字符都可以。但是,如果用戶想要輸入多行,我該怎麼做?這些函數一次只輸出一行的結果,而不是將兩行的結果相加。另外,我無法使獨特線條和獨特詞語正常工作。我剛剛進入C++,所以我沒有太多經驗。有人可以幫幫我嗎?獨特的線條和單詞?如何實現它?
問題:
- 程序讀取在每次一行,所以當用戶輸入多次,程序分別生成結果,而不是增加其一起作爲一個實體。
唯一線條和唯一字詞不起作用。任何想法如何使用該程序中使用的庫來實現它。
#include <iostream> using std::cin; using std::cout; using std::endl; #include <string> using std::string; #include <set> using std::set; // write this function to help you out with the computation. unsigned long countLines() { return 1; } unsigned long countWords(const string& s) { int nw =1; for (size_t i = 0; i < s.size(); i++) { if (s[i] == ' ') //everytime the function encounters a whitespace, count increases by 1)// { nw++; } } return nw; } unsigned long countChars(const string& s) { int nc = 0; for (size_t i = 0; i < s.size(); i++) { if (s[i] != ' ') //everytime the function encounters a character other than a whitespace, count increases// { nc++; } } return nc; } unsigned long countUnLines(const string& s, set<string>& wl) { wl.insert(s); return wl.size(); } unsigned long countUnWords(const string& s, set<string>& wl) { int m1 = 0; int m2 = 0; string substring; for(m2 = 0; m2 <= s.size(); m2++){ if (m2 != ' ') substring = s.substr(m1,m2); wl.insert(substring); m1 = m2 + 2;} } return wl.size(); int unw = 0; wl.insert(s); unw++; return unw; } int main() { //stores string string s; //stores stats unsigned long Lines = 0; unsigned long Words = 0; unsigned long Chars = 0; unsigned long ULines = 0; unsigned long UWords = 0; //delcare sets set<string> wl; while(getline(cin,s)) { Lines += countLines(); Words += countWords(s); Chars += countChars(s); ULines += countUnLines(s,wl); UWords += countUnWords(s); cout << Lines << endl; cout << Words<< endl; cout << Chars << endl; cout << ULines << endl; cout << UWords << endl; Words = 0; Chars = 0; ULines = 0; UWords = 0; } return 0; }
您顯示了很多註釋行,其中很多回答了您所問的問題。你現在發佈的內容不會運行,因爲'main'被註釋掉了,但是在那裏,它正確地讀取了行。將你的'cout'移到while循環的外部,並在循環結束時刪除所有的東西到0。此外,檢查行中單詞的代碼有一個錯誤:「一個單詞[6個空格]和一個」'將導致8個單詞。 –