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;
}
count 的 cout 为每个计数删除一个字符。 这是为什么? 还有为什么我不能在计数后加上“\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
, +
确实附加了两个字符串。但仍然是 <<
version 效率更高,因为它无需构造任何新字符串即可输出数据。
关于c++ - Cout 里面 while?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62761666/