c++ - Cout 里面 while?

标签 c++

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";

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

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

相关文章:

c++ - 使用 C 样式字符串文字与构造未命名的 std::string 对象的默认建议?

c++ - 这个函数有什么作用?

c++ - Gtkmm - 更改窗口的最小尺寸

c++ - 类私有(private)变量损坏

c++ - Ifstream 在几行后停止读取文件

c++ - 我们可以使用 "this"指针获取对象名称吗

c++ - 在某个内存区域中查找字节模式

c++ - 为什么插槽作为字符串传递? Qt

c++ - 与指针一起使用时未声明“开始”

c++ - 了解如何解决 C++ 中不明确的成员请求