我在使用这个程序时遇到了问题。该程序应该告诉用户在给定输入中存在的行数、单词数、字符数、唯一行数和唯一单词数。到目前为止,单词和字符都还可以。但是,如果用户想要输入多行,我该怎么做呢?这些函数一次只输出一行的结果,而不是将两行的结果相加。此外,我无法让独特的线条和独特的单词正常工作。我刚接触 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; }