首页 > 解决方案 > Cout 在里面吗?

问题描述

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

计数的 cout 正在为每个计数删除一个字符。这是为什么?还有为什么我不能在计数后加上“\n”?

谢谢

输出:

ha ho ha ha 重复词: ha
t 重复词: hi ho ho 重复词: ho f 重复词:

标签: c++

解决方案


你清楚地认为这段代码

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

将附加count到输出的其余部分,但它没有。如果您想知道指针算术的真正作用,请查看指针算术,尽管“为每个计数删除一个字符”是一个合理的总结。

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

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

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

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

虽然在那种情况下因为current是 a string+但确实会附加两个字符串。但是该<<版本仍然更有效,因为它在不构造任何新字符串的情况下输出数据。


推荐阅读