c++ - 用输入给出的单词填充字符串

标签 c++ string iterator char

输入:

今天我吃面包。今天我吃 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 然后您取消引用该迭代器并将其分配给它,您不允许这样做,因为它是常量

再试一次 string::iterator

关于c++ - 用输入给出的单词填充字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22116877/

相关文章:

Java,一个集合上的多个迭代器,删除适当的子集和 ConcurrentModificationException

nullpointerexception - [WSO2 ESB][4.9.0] NPE 在发回时进行迭代

c++ - 包含 unordered_map 作为成员的结构的 sizeof()

c - 从字符串中反转子字符串

javascript - 如何从字符串中获取奇数和偶数位置的字符?

c# - 拆分字符串并将分隔符保留为新的结果项

python -++增量运算符的等价物是什么?

c++ - Rust 的 Drop 和 C++ 的析构函数有什么区别?

c++ - 是否有 BOOST_FOREACH 的免 boost 版本?

c++ - 运算符重载可以在没有引用的情况下工作吗?