getline() & stringstream

/* 處理多行測資 */
#include <iostream>
#include <sstream>
using namespace std;
 
int main() {
    string s;
    stringstream ss; //只宣告一次

    while (getline(cin, s)) {
        //初始化 ss (下面第一行必須,第二行可以避免一些異常現象)
        //ss.str(""); //reset to an empty string
        ss.clear(); //clear any fail and EOF flags
        ss << s; //賦值
        while (ss >> s){
            //只印出每一行的前兩個字串
            cout << "=" << s << "=";
            ss >> s;
            cout << "=" << s << "=";
            break;
        }
        cout << "(next)\n";
    }
    return 0;
}
Example Input:
AA BB CC
DD EE FF
GG HH II

期望的結果:
=AA==BB=(next)
=DD==EE=(next)
=GG==HH=(next)
只執行第12行的話,在這個例子剛好正確。(但未必總是如此)
=AA==BB=(next)
=DD==EE=(next)
=GG==HH=(next)
只執行第13行的話,ss 未被清空。
=AA==BB=(next)
=CCDD==EE=(next)
=FFGG==HH=(next)
/* 處理多行測資 */
#include <iostream>
#include <sstream>
using namespace std;
 
int main() {
    string s;
    while (getline(cin, s)) {
        stringstream ss(s); //只宣告一次,同時賦值,少了reset的困擾,但速度較慢
        while (ss >> s){
            //只印出每一行的前兩個字串
            cout << "=" << s << "=";
            ss >> s;
            cout << "=" << s << "=";
            break;
        }
        cout << "(next)\n";
    }
    return 0;
}
分享本文 Share with friends