gpt4 book ai didi

c++ - 产生时髦输出的程序

转载 作者:太空宇宙 更新时间:2023-11-04 12:56:17 24 4
gpt4 key购买 nike

我正在编写一个程序,该程序从 std::cin 接收输入流,然后用输入中的所有单词(在删除所有标点符号并使其小写后)及其出现频率填充一个映射容器。

这是我的代码...

#include "prog4.h"


void clean_entry(const string& s1, string& s2) {
for (int i = 0; i < s2.size(); i++) {//loop through the string
s2[i] = tolower(s2[i]);
}
}

void get_words(map < string, int >& map1) {
string input;
getline(cin, input);
string s1;
for (int i = 0; i < input.size(); i++ , s1 = "") {//loop through
entire input
if (isalnum(input[i]) == 0) {//if its a alphanumeric char
for (int d = i; isalnum(input[d]) == 0;d++) {//make s1 the
next set of characters between punctuation
s1 += input[d];

if (isalnum(input[d]) != 0)//update i to the next non
alfanumeric character position
i = d;
}
}
clean_entry(s1, s1);
map1[s1]++;
}

}

void print_words(const map < string, int >& m1) {
map<string, int>::const_iterator it;
cout << "Number of non-empty words: " << m1.size() << '\n';
int count = 0;
for (it = m1.begin(); it != m1.end(); it++) {
if (it->second == 1)
count++;
}
cout << "Number of distinct words: " << count << '\n';
it = m1.begin();
for (int y = 0; it != m1.end(); it++,y++) {
if (y % 3 == 0) {
cout << '\n';
}
cout << setw(20) << it->first << setw(10) << it->second;
}
}

int main() {
map <string, int> m1;
get_words(m1);
print_words(m1);

return 0;
}

我已经测试了 print 和 clean 方法,它们都按预期工作。我遇到的问题是当我毫无疑问地使用 get_words 方法时。

例如,当我使用输入“Huge Muge Cuge luge”时,这就是我得到的输出...

Number of non-empty words: 2
Number of distinct words: 0


16 3

我不确定是什么导致了这种情况发生,在查看代码后我似乎找不到问题,这就是我在这里发帖的原因

最佳答案

让我列出我在您的代码中观察到的几个问题。

  1. isalnum 函数返回字母数字字符的非零值。这意味着声明if (isalnum(input[i]) == 0) { 函数 get_words 应该改为if (isalnum(input[i]) != 0) {

此外,声明 for (int d = i; isalnum(input[d]) == 0;d++) { 应该更改为 for (int d = i; isalnum(输入[d]) != 0;d++) {

  1. 另一个问题是语句 i = d; 将不会执行,因为当 for 循环中断时它将跳过这些行,因为条件恰好相反。您可以通过将 d 的声明移出 for 循环来解决此问题。修改后的函数应该是:

=>

void get_words(map < string, int >& map1) 
{
string input;
getline(cin, input);
string s1;
for (int i = 0; i < input.size(); i++ , s1 = "")
{
if (isalnum(input[i]) != 0)
{//if its a alphanumeric char
int d;
for (d = i; isalnum(input[d]) != 0;d++)
{
s1 += input[d];
}
if (isalnum(input[d]) == 0)
i = d;
}
clean_entry(s1, s1);
map1[s1]++;
}
}

关于c++ - 产生时髦输出的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46515436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com