输入:
今天我吃面包。今天我吃 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/