2017-10-10 6 views
0

コマンドラインの文字列を解析しようとしていますが、文字列に引用符で囲んだ文字列を考慮して空白を入れてみます。私は2つの引用符の間にあるものをベクトルの1つのインデックスとして保存したい。引用符の間の引数を考慮に入れる

vector<string> words; 
stringstream ss(userInput); 
string currentWord; 
vector<string> startWith; 
stringstream sw(userInput); 

while (getline(sw, currentWord, ' ')) 
    words.push_back(currentWord); 

while (getline(ss, currentWord, '"')) 
startWith.push_back(currentWord); //if(currentWord.compare("")){ continue;} 

for (int i = 0; i < startWith.size(); i++) 
    curr 
    if(currentWord.compare("")){ continue;} 
    cout << " Index "<< i << ": " << startWith[i] << "\n"; 
+0

[STD ::引用されたが(http://en.cppreference.com/w/cpp/io/manip /引用) – ZDF

+0

@ZDFこれはC++ 11以降、C++ 14以降では利用できません。 – Murphy

+0

@Murphy Correct。 – ZDF

答えて

0

あなたがしようとしていることは明確ではありません。

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

std::istream& get_word_or_quote(std::istream& is, std::string& s) 
{ 
    char c; 

    // skip ws and get the first character 
    if (!std::ws(is) || !is.get(c)) 
    return is; 

    // if it is a word 
    if (c != '"') 
    { 
    is.putback(c); 
    return is >> s; 
    } 

    // if it is a quote (no escape sequence) 
    std::string q; 
    while (is.get(c) && c != '"') 
    q += c; 
    if (c != '"') 
    throw "closing quote expected"; 

    // 
    s = std::move(q); 
    return is; 
} 

int main() 
{ 
    std::istringstream is {"not-quoted \"quoted\" \"quoted with spaces\" \"no closing quote!" }; 

    try 
    { 
    std::string word; 
    while (get_word_or_quote(is, word)) 
     std::cout << word << std::endl; 
    } 
    catch (const char* e) 
    { 
    std::cout << "ERROR: " << e; 
    } 

    return 0; 
} 

予想される出力は次のとおりです:ここで出発点(run it)です

not-quoted 
quoted 
quoted with spaces 
ERROR: closing quote expected 
関連する問題