2013-02-06 144 views
0

我正在讀取來自諸如「5 8 12 45 8 13 7」等文件的輸入行。C++將整數字符串轉換爲整數數組?

我可以將這些整數直接放入數組中,還是必須先將它們放入一個字符串?

如果最初使用一個字符串是強制性的,我該如何將這個整數字符串轉換爲一個數組?

輸入: 「5 8 12 45 8 13 7」=>到一個數組爲這樣:{5,8,12,45,8,13,7}

+0

你怎麼讀線路?請張貼該代碼:它是相關的。 –

+2

我相信這個問題是以下內容的副本: http://stackoverflow.com/questions/1321137/convert-string-containing-several-numbers-int-integers http://stackoverflow.com/questions/ 1894886/parsing-a-comma-delimited-stdstring http://stackoverflow.com/questions/4170440/regex-how-to-find-the-maximum-integer-value-of-a-pattern http:// stackoverflow.com/questions/2619227/best-way-to-get-ints-from-a-string-with-whitespace http://stackoverflow.com/questions/1141741/int-tokenizer –

回答

7

否,則不需要將它們轉換爲一個字符串。與C++標準庫的容器和算法它實際上是很容易的(這個工程只要分隔符是空格或空格的序列):

#include <iterator> 
#include <iostream> 
#include <vector> 

int main() 
{ 
    std::vector<int> v; 

    // An easy way to read a vector of integers from the standard input 
    std::copy(
     std::istream_iterator<int>(std::cin), 
     std::istream_iterator<int>(), 
     std::back_inserter(v) 
     ); 

    // An easy wait to print the vector to the standard output 
    std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " ")); 
} 
+0

如何打印此數組?對不起,我正在用這種語言苦苦掙扎。 –

+0

@AaronPorter:我添加了一個簡單的方法將矢量打印到標準輸出。請考慮接受這個答案,如果它幫助你。 –

+2

@AndyProwl他也可以考慮查看覆蓋這個特殊問題的重複問題清單。 –