亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

解析逗號分隔的std:string

解析逗號分隔的std:string

C++
三國紛爭 2019-06-28 10:19:29
解析逗號分隔的std:string如果我有一個包含逗號分隔的數字列表的std:string,那么解析這些數字并將它們放入整數數組的最簡單方法是什么?我不想把它概括為解析其他任何東西。只是一個簡單的逗號分隔整數字符串,如“1,1,1,1,2,1,1,1,0”。
查看完整描述

3 回答

?
慕神8447489

TA貢獻1780條經驗 獲得超1個贊

不那么冗長的東西,用逗號隔開的東西。

stringstream ss( "1,1,1,1, or something else ,1,1,1,0" );vector<string> result;while( ss.good() ){
    string substr;
    getline( ss, substr, ',' );
    result.push_back( substr );}


查看完整回答
反對 回復 2019-06-28
?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

還有一種非常不同的方法:使用特殊的區域設置,將逗號作為空白:

#include <locale>#include <vector>struct csv_reader: std::ctype<char> {
    csv_reader(): std::ctype<char>(get_table()) {}
    static std::ctype_base::mask const* get_table() {
        static std::vector<std::ctype_base::mask> rc(table_size, std::ctype_base::mask());

        rc[','] = std::ctype_base::space;
        rc['\n'] = std::ctype_base::space;
        rc[' '] = std::ctype_base::space;
        return &rc[0];
    }};

用這個,你imbue()包含此方面的區域設置的流。一旦你這樣做了,你就可以讀數字,就好像逗號根本不存在一樣。例如,我們將從輸入中讀取逗號分隔的數字,然后在標準輸出中寫出一行:

#include <algorithm>#include <iterator>#include <iostream>int main() {
    std::cin.imbue(std::locale(std::locale(), new csv_reader()));
    std::copy(std::istream_iterator<int>(std::cin), 
              std::istream_iterator<int>(),
              std::ostream_iterator<int>(std::cout, "\n"));
    return 0;}


查看完整回答
反對 回復 2019-06-28
  • 3 回答
  • 0 關注
  • 2104 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號