2016-10-01 91 views
1

嘗試將一些逗號分隔值從字符串中加在一起。我覺得我需要刪除逗號。這是stringstream的情況嗎?C++添加逗號分隔值

string str = "4, 3, 2" 
//Get individual numbers 
//Add them together 
//output the sum. Prints 9 
+1

你說得對。一個解決方案是std :: istringstream與std :: getline結合 –

+0

歡迎使用Stack Overflow。你有什麼嘗試? –

回答

1

我會用istringstreamgetline在while循環分裂(記號化)逗號周圍的字符串。 然後只需使用std::stoi將每個字符串標記轉換爲整數,然後將該數字添加到總和。 std::stoi放棄字符串輸入中的任何空白字符。

std::string str = "4, 3, 2"; 
std::istringstream ss(str); 

int sum = 0; 
std::string token; 
while(std::getline(ss, token, ',')) { 
    sum += std::stoi(token); 
} 
std::cout << "The sum: " << sum; 
+1

謝謝!它完美的工作! –