2013-02-13 66 views
-1

你能,請幫助得到這個格式的輸入:閱讀陣列格式輸入

{1,2,3,4} 

,並與整數轉換爲數組?

int * ns = new int [n]; 
    cin >> ns; 

這不起作用。我應該如何改變它?

+0

因爲它的C++,答案的第一部分將是「使用'std :: vector'而不是'new int [n]'」。 – 2013-02-13 12:49:19

+0

不,用戶鍵入輸入 – Bek 2013-02-13 12:55:29

回答

0
using namespace std; 
typedef istream_iterator<int> It; 
vector<int> v; 
copy(It(cin), It(), back_inserter(v)); 
+0

它是如何工作的? – 2013-02-13 12:55:35

+0

您可以閱讀我使用的功能的文檔。它只是將所有可以從std :: cin的複製到矢量中。 – 2013-02-13 12:56:48

+0

它沒有,與指定的輸入:http://ideone.com/nvG1bE – Johnsyweb 2013-02-13 12:57:24

0

您需要逐個讀取元素並將它們存儲到數組中。

int aNoOfElements = 0; 
cin >> aNoOfElements; 
int *anArray = new int[ aNoOfElements];  //allocate memory to hold aNoOfElements 

for(int i = 0; i < aNoOfElements; i++) 
{ 
    cin >> anArray[ i ];     // Read each input 
} 
0

您需要解析輸入。以字符串形式輸入,然後檢查符合您需要的格式。一種算法,您可以使用:

  1. 檢查的第一個字符是「{」
  2. 如果是,則初始化變量(比如溫度)來保存你即將獲得的數量(作爲字符串)與空字符串,否則錯誤
  3. 下一個讀取字符
  4. ,如果它是「0」之間的「9」,然後將其追加到temp中,並返回到第3步,否則到步驟5
  5. 如果它是一個逗號或'}',然後將temp轉換爲整數並將其放入數組中,用空字符串重新初始化temp,否則錯誤
  6. 仍然在相同的字符,如果它是一個逗號,然後回到步驟3,否則做

我希望你可以把上面的算法形成工作代碼,好運:)

PS:歡迎告訴我你是否發現了一個bug