4

次のコードを実行中にエラーが 1 回発生します

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main (int argc, char* argv[]){
    string tokens,input;
    input = "how are you";
    istringstream iss (input , istringstream::in);
    while(iss){
        iss >> tokens;
        cout << tokens << endl;
    }
    return 0;

}

最後のトークン「you」を 2 回出力しますが、次の変更を行うとすべて正常に動作します。

 while(iss >> tokens){
    cout << tokens << endl;
}

while ループがどのように動作しているのか、誰か説明してもらえますか。ありがとう

4

1 に答える 1

9

それは正しいです。条件は、ストリームの終わりを過ぎて読み取った後にwhile(iss)のみ失敗します。したがって、ストリームから抽出した後も、それは真実です。"you"

while(iss) { // true, because the last extraction was successful

だからあなたはもっと抽出しようとします。この抽出は失敗しますが、 に格納されている値には影響しないため、tokens再度出力されます。

iss >> tokens; // end of stream, so this fails, but tokens sill contains
               // the value from the previous iteration of the loop
cout << tokens << endl; // previous value is printed again

まさにこの理由から、提示した 2 番目のアプローチを常に使用する必要があります。そのアプローチでは、読み取りが失敗した場合、ループには入りません。

于 2012-01-24T07:00:12.250 に答える