c++ - 关于练习的问题(Bjarnes PPP 书籍)
问题描述
为什么当我输入由空格分隔的字符串(在while循环之外)并且我尝试在屏幕上打印它们时,只有我输入的第一个出现并且在这个while循环中(参见代码)它会一个接一个地打印它们?
//this one prints the strings one by one
string current;
while (cin >> current) {
cout << current << " \n";
}
//this one only prints the first one the user types
string current;
cin >> current;
cout << current << " \n";
解决方案
这是cin
默认的操作方式。它跳过任何空格,读取到下一个空格,然后返回该字符串。如果您输入:
testing cin input
您需要执行cin
3 次才能获得每个单词。这就是while
循环中发生的事情。
我提到“默认情况下”,因为您可以将行为更改为不跳过空格。
推荐阅读
- sql - Postgres Trigrams 和排序非常慢
- salesforce - 如何通过rest api获取我的visualforce页面顶点代码?
- cookies - 是否必须在移动网站上显示 cookie 政策通知?
- c# - C# DateTime 解析不一致
- node.js - 我想使用 webrtc 在 nodejs 中实现对等视频通话
- button - 有没有办法告诉CMFCColorButton,不呈现什么颜色
- amazon-web-services - aws cloudformation appsync 扩展查询?
- django - Django中的多个查询优化
- java - 使用 System.nanoTime() 时比较如何导致数值溢出
- asp.net-mvc - 通过模型定义剑道网格