[英]Code gets stuck in loop (but loop itself doesn't keep going). C++ string
我目前正在使用 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 停止程序。
对于一个非常简单的问题,这是一个非常复杂的方法。 您可以只使用stringstream
来提取由空格分隔的每个单词。 然后,您只需提取提取的单词并使用std::map<std::string, int>
递增单词计数器。
我对此的看法:
#include <iostream>
#include <map>
#include <string>
#include <sstream>
int main() {
std::map<std::string, int> word_to_count;
std::string in;
std::getline(std::cin, in);
std::stringstream s(in);
std::string temp_word;
while (s >> temp_word) {
word_to_count[temp_word]++;
}
for (const auto& x : word_to_count) {
std::cout << x.first << ": " << x.second << std::endl;
}
return 0;
}
hello world hello world test
hello: 2
test: 1
world: 2
请记住,这只是许多可能的解决方案之一,因此请以此为灵感:)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.