CPP

Simple way to split a string in C++

รูปภาพของ hiddenmin

สำหรับคนที่เคยใช้ python ก็คงจะคุ้นเคยกับคำสั่ง split() ที่เอาไว้แยกแต่ละคำในตัวแปรแบบ string แต่ใน C++ ดันไม่มีคำสั่ง (ง่ายๆ) แบบนั้น

หลังจากใช้เวลาค้นหาไปพักใหญ่ๆ ก็ได้โค้ดแบบนี้

#include <iostream>
#include <sstream>

using namespace std;

int main(){
    string rawStr;
    getline(cin, rawStr);
    stringstream ss(rawStr);
    string buff;
    while(ss >> buff){
        cout << buff << endl; // this 's what i want
    }

    return 0;
}

Tags: 

Subscribe to RSS - CPP