【发布时间】:2021-02-06 11:40:23
【问题描述】:
我目前正在使用 Schaum 的大纲书(主要涵盖 C 内容,或者有人告诉我,但无论如何)自学 C++,并且遇到了问题 9.8 的一些问题。 您应该计算给定 c++ 字符串中每个不同单词的出现次数,为此我假设每个单词与下一个单词之间用空格、换行符或点或逗号分隔(在最后两种情况下)由另一个空白区域)。 我的代码如下:
#include <iostream>
#include <string>
using namespace std;
int main()
{ string s;
cout << "Enter text (enter \"$\" to stop input):\n";
getline(cin,s,'$');
string s2 = s, word;
int ini = 0, last, count_word = 0;
int count_1 = 0, count_2 = 0, count_3 = 0;
cout << "\nThe words found in the text, with its frequencies, are the following:\n";
for (ini; ini < s.length(); )
{ // we look for the next word in the string (at the end of each iteration
// ini is incremented in a quantity previous_word.length()
last = ini;
cout << "1: " << ++count_1 << endl;
while(true)
{ if (s[last] == ' ') break;
if (s[last] == '\n') break;
if (s[last] == ',') break;
if (s[last] == '.') break;
if (last > s.length()-1 ) break;
++last;
cout << "2: " << ++count_2 << endl;
}
--last; // last gives the position within s of the last letter of the current word
// now me create the word itself
word = s.substr(ini,last-ini+1); //because last-ini is word.length()-1
int found = s2.find(word);
while( found != s2.length() ) // the loop goes at least once
++count_word;
s2.erase(0,found+word.length()); // we erase the part of s2 where we have already looked
found = s2.find(word);
cout << "3: " << ++count_3 << endl;
cout << "\t["<<word<<"]: " << count_word;
++last;
s2 = s;
s2.erase(0,ini + word.length()); // we do this so that in the next iteration we don't look for
// the new word where we know it won't be.
if (s[last] == ' ' || s[last] == '\n') ini = last + 1;
if (s[last] == ',' || s[last] == '.') ini = last + 2;
count_word = 0;
}
}
当我运行程序时,屏幕上什么也没有显示,所以我发现其中一个循环一定是卡住了(这就是我定义变量 count_1,2 和 3 的原因,以了解是否是这样)。 但是,在正确计算要找到的第一个单词的迭代次数后,没有打印任何其他内容,我看到的只是命令提示符(我的意思是小白条),我什至无法使用 ctrl z 停止程序。
【问题讨论】:
-
如果你在调试器下运行程序员,当它“陷入循环”时,你可以点击“暂停”。这会告诉你你需要知道的一切。
-
您的
while( found != s2.length() )循环缺少大括号,因此它只会在循环中运行下一行 (++count_word;),而不是所有缩进语句。由于++count_word永远无法更改found的值,因此循环将永远继续。 -
我检查了第二个 while 循环中没有大括号,这很好。问题仍然在于第三个循环,但我找不到它。