2013-03-10 78 views
-6

我有一個五個值的字符串,每個值由一個空格分隔。在C++中,如何將一個字符串拆分爲多個整數?

std::string s = "123 123 123 123 123"; 

如何將它們分成五個整數數組?

+0

讀約與strtol()http://www.cplusplus.com/reference/cstdlib/strtol/ – 2013-03-10 16:36:30

+0

如果搜索在C++字符串分割,然後將字符串轉換在C++的數字,你會得到你問題在5分鐘內徹底解決了。 – Mat 2013-03-10 16:37:37

回答

7

使用std::stringstream像這樣:

#include <sstream> 
#include <string> 

... 

std::stringstream in(s); 
std::vector<int> a; 
int temp; 
while(in >> temp) { 
    a.push_back(temp); 
} 
+0

或者更好的是,構建'的std :: VECTOR'這樣'的std ::向量 V((的std :: istream_iterator (ISS))的std :: istream_iterator ());'(需'的#include ')。 – Snps 2013-03-10 17:05:56

0

試試這個,如果你需要一個內置的陣列,但它通常是更好地使用std::vector,如前所說,在一般情況下。我假設你想在每個空格字符處分割字符串。

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

int main() { 
    std::string s = "123 123 123 123 123"; 
    std::istringstream iss(s); 

    int arr[5]; 
    for (auto& i : arr) { 
     iss >> i; 
    } 
} 
相關問題