2016-03-26 7 views

答えて

3

区切り文字が1文字の場合は、std::istringstreamとカスタム区切り文字を使用してstd::getlineを使用できます。

const auto text = std::string {"alpha,beta,gamma"}; 
const auto delim = ','; 
auto token = std::string {}; 
auto iss = std::istringstream {text}; 
while (std::getline(iss, token, delim)) 
    std::cout << "Parsed token: '" << token << "'\n"; 

また、regular expressionを使用することもできます。

const auto text = std::string {"alpha,beta,gamma"}; 
const auto pattern = std::regex {"[^,]+"}; 
const auto first = std::sregex_iterator {text.cbegin(), text.cend(), pattern}; 
const auto last = std::sregex_iterator {}; 
for (auto it = first; it != last; ++it) 
    std::cout << "Parsed token: '" << it->str() << "'\n"; 

いずれのソリューションも、おそらくstd::sscanfを使用するよりもはるかに遅くなります。

1

あなたの場合、,を含むstringを分割したいとします。これを実現するにはgetlinestringstreamを使用できます。

まず、あなたはその後stringstream

stringstream ss(line); 

を使用してストリームにstringを変更、あなたがtmpを使用することができ、最終的には,

while(getline(ss,tmp,',')) //Here you use string tmp to save it 

デリミタ使用して、それを分割するgetlineを使用することができますし、それをvector <string>に押し込みます。ここには完全なプログラムの例があります。

#include<bits/stdc++.h> 
#include<sstream> 
using namespace std; 
int main(){ 
    string line = "data1,data2,data3"; 
    stringstream ss(line); 
    vector <string> result;string tmp; 
    while(getline(ss,tmp,',')){ 
     result.push_back(tmp); 
    } 
    return 0; 
} 
関連する問題