int main() {
int count = 0;
string prev = " ";
string current;
while (cin>>current)
{
++count;
if (prev == current)
{
cout << "count of repeated: " << count << "\n" << "repeated words: " + current + "\n";
}
prev = current;
}
}
这有效,但是当我使用时: if (prev == current)
{
cout << "repeated words: " + current + "\n";
cout << "count of repeated words: " + count;
}
计数的指示项是为每个计数删除一个字符。这是为什么?
还有为什么我不能在计数后加上“\ n”?
谢谢
输出:
哈
浩
哈
哈
重复的话:哈
重复字词t:
你好
浩
浩
重复的话:ho
f重复的单词:
最佳答案
您清楚地认为这段代码
cout << "count of repeated words: " + count;
将把count
附加到输出的其余部分,但是没有。如果您想了解指针的实际功能,请查找指针算法,不过“合理地总结一下”为每个计数删除一个字符”。得到想要的东西的方法是
cout << "count of repeated words: " << count << "\n";
同样,您的第一行最好这样写cout << "repeated words: " << current << "\n";
尽管在这种情况下,因为current
是string
,所以+
实际上确实附加了两个字符串。但是<<
版本仍然更有效,因为它无需构造任何新字符串即可输出数据。关于c++ - 里面有Cout吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62761666/