>current) -6ren">
gpt4 book ai didi

c++ - Cout 里面 while?

转载 作者:行者123 更新时间:2023-12-01 14:36:40 28 4
gpt4 key购买 nike

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 重复词:你好呵呵呵呵重复的词:hof 重复的词:

最佳答案

你明明以为这段代码

cout << "count of repeated words: " + count;

将追加 count到输出的其余部分,但事实并非如此。如果您想了解它的真正作用,请查阅指针算术,“为每个计数删除一个字符”是一个合理的总结。

得到你想要的方法是这样的

cout << "count of repeated words: " << count << "\n";

同样,你的第一行最好这样写

cout << "repeated words: " << current << "\n";

虽然在那种情况下因为 currentstring , +确实附加了两个字符串。但仍然是 << version 效率更高,因为它无需构造任何新字符串即可输出数据。

关于c++ - Cout 里面 while?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62761666/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com