複数行データから1行抜き出しサンプル(C++)
複数行のデータから一行だけ抜き出すサンプルです。
行ごとにベクターに格納されていき、最後の行が改行コードで終わっていない場合はsorceに残されます。
シリアル通信なんかで必ず一行来るとは限らない時なんかに便利です。
行ごとにベクターに格納されていき、最後の行が改行コードで終わっていない場合はsorceに残されます。
シリアル通信なんかで必ず一行来るとは限らない時なんかに便利です。
#include <iostream> #include <vector> #include <string> using namespace std; int readLine( string sorce , vector<string> &data ) { string temp = sorce; int pos; //データを分解し、ベクターに入れていく while( true ) { pos = temp.find( "\n" ); if( pos != string::npos ) { data.push_back(temp.substr( 0 , pos )); } else { data.push_back(temp); break; } pos++; //改行コード分ずらす temp = temp.substr( pos , temp.size() - pos ); if( temp == "" ) break; } cout << data.size() << endl; for( int i = 0 ; i < data.size() ; i++ ) cout << data[i] << endl; return 0; } int main() { string sorce = "<tag>flanker7711</tag>\n<tagB>include</tagB>\n" ; vector<string> data; readLine( sorce , data ); return 0; }