首页 > 解决方案 > 关于练习的问题(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";

标签: c++

解决方案


这是cin默认的操作方式。它跳过任何空格,读取到下一个空格,然后返回该字符串。如果您输入:

    testing cin input

您需要执行cin3 次才能获得每个单词。这就是while循环中发生的事情。

我提到“默认情况下”,因为您可以将行为更改为不跳过空格。


推荐阅读