用输入中给出的单词填充字符串



输入:

Today I eat bread. Today I eat cookies.

输出:

eat: 2
        
I: 2
        
Today: 2
bread: 1
cookies: 1

我必须制作一个程序来计算单词在输入中出现的次数。然后,如果某些单词之间的次数相等,则我按字母顺序显示它们。到目前为止,我这样做:

#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int countt (string text);
int main () {
    string text;
    while (getline(cin,text))     //Receive the input here
    countt(text);                //Send the input to countt
    return 0;
}
int countt (string text) {
    int i,j;
    string aux;     //I make a string aux to put the word to compare here
        for (std::string::const_iterator i = text.begin(); *i != ' '; i++){
            for (std::string::const_iterator j = aux.begin(); j != text.end(); j++)
                *j=*i; //But here an error is given: 25:9: error: assignment of read-only location ‘j.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator*<const char*, std::basic_string<char> >()’
        }
        }

提前非常感谢。

具体指代码中的错误注释:

for循环中,您正在使用const_iterator,然后取消引用该迭代器并分配给它,这是不允许这样做的,因为它是const的。

使用string::iterator重试。

将一行读入字符串,就像你现在所做的那样。但随后使用 std::istringstream 标记输入。使用 std::unordered_map 将单词存储为键,将计数存储为数据。

最新更新