C++ - Storing user input string separated by commas into vector

前端 未结 3 1375
野趣味
野趣味 2021-01-07 09:23

I have a code written that performs this task to a certain extent. But, I would like to how to alter my code so that I can store as many string inputs the user wants to ente

3条回答
  •  情歌与酒
    2021-01-07 10:03

    You can see running code here or as a github gist.

    // Example program
    #include 
    #include 
    #include 
    #include 
    
    void ParseCSV(
        std::vector< std::string >& output,
        const std::string& csv )
    {
    
        int q = 0;
        int p = csv.find(",");
        while( p != -1 )
        {
            output.push_back( csv.substr(q,p-q) );
            q = p+2;
            p = csv.find(",",q);
        }
    
        // The terminating comma of the CSV is missing
        // so we need to check if there is
        // one more value to be appended
    
        p = csv.find_last_of(",");
        if( p != -1 )
        {
            output.push_back( csv.substr( p+2 ) );
    
        }
        else
        {
            // there was no comma
            // this could be because the list is empty
            // it could also be because there is just one element in the list
    
            if( csv.length() > 1 )
                output.push_back( csv );
        }
    }
    
    int main()
    {
        std::string test("this is my list, a, b, c, d, end of line");
        std::vector< std::string > split;
        ParseCSV( split, test );
        for( auto& s : split )
            std::cout << s << std::endl;
    
    }
    

    As suggested by Christophe, using stringstream is much better. No special case handling needed! I use a while loop - it seems clearer what is happening.

    void ParseCSV2(
        std::vector< std::string >& output,
        const std::string& csv )
    {
        std::stringstream sst(csv);
        std::string a;
        while( getline( sst, a, ',' ) )
            output.push_back(a);
    }
    

提交回复
热议问题