我遇到了这个程序的麻烦。该程序应该告诉用户在给定输入中有多少行,单词,字符,唯一行和唯一字。到目前为止,文字和字符都可以。但是,如果用户想要输入多行,我该怎么做?这些函数一次只输出一行的结果,而不是将两行的结果相加。另外,我无法使独特线条和独特词语正常工作。我刚刚进入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个单词。 –