[英]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.