c++ - 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 重复词:
解决方案
你清楚地认为这段代码
cout << "count of repeated words: " + count;
将附加count
到输出的其余部分,但它没有。如果您想知道指针算术的真正作用,请查看指针算术,尽管“为每个计数删除一个字符”是一个合理的总结。
得到你想要的方法是这样的
cout << "count of repeated words: " << count << "\n";
同样,您的第一行最好这样写
cout << "repeated words: " << current << "\n";
虽然在那种情况下因为current
是 a string
,+
但确实会附加两个字符串。但是该<<
版本仍然更有效,因为它在不构造任何新字符串的情况下输出数据。
推荐阅读
- php - htaccess 仅重定向主目录
- android - 在开发人员选项中获取触摸形状
- ruby-on-rails - 每次在rails 5.1上自动创建父对象时如何生成子对象
- html - 悬停时带有列表的菜单按钮和嵌套菜单
- emacs - 为什么 Emacs 在按下向下箭头时会在文件末尾添加新行?
- python - 更新:Odoo 项目任务标签域
- java - 线程“主”java.lang.UnsatisfiedLinkError 中的异常:java.library.path 中没有 opencv_java320
- php - 如何将 Odoo 数据库与 Laravel 集成?
- python - python selenium点击页面按钮
- android - 我应该如何将进度条添加到 Xamarin.Android 中的操作栏?