2013-06-05 30 views
0

我正試圖解決用戶必須輸入數字n的情況。然後在同一行上輸入n個數字。因此,我的程序需要在用戶繼續輸入之前知道這個數字n,以便程序知道它需要多大的動態數組才能保存n之後輸入的這些數字。 (所有這一切發生在一條線上是至關重要的)。在按下空格時獲取用戶輸入

我試過以下,但它似乎並沒有工作。

int r; 
cin >> r; 

//CL is a member function of a certain class 
CL.R = r; 
CL.create(r); //this is a member function creates the needed dynamic arrays E and F used bellow 

int u, v; 
for (int j = 0; j < r; j++) 
{ 
    cin >> u >> v; 
    CL.E[j] = u; 
    CL.F[j] = v; 
} 
+0

你應該使用'std :: vector',否則這個解析解決方案對我來說工作的很好。什麼不工作? – Suedocode

+0

爲什麼您希望用戶使用空格而不是輸入分隔號碼?我的鍵盤在數字鍵盤中包含一個「Enter」鍵。 –

回答

2

你可以做到這一點像往常一樣在同一行:

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

using namespace std; 

int main() 
{ 
    int *array; 
    string line; 
    getline(cin,line); //read the entire line 
    int size; 
    istringstream iss(line); 
    if (!(iss >> size)) 
    { 
    //error, user did not input a proper size 
    } 
    else 
    { 
    //be sure to check that size > 0 
    array = new int[size]; 
    for (int count = 0 ; count < size ; count++) 
    { 
     //we put each input in the array 
     if (!(iss >> array[count])) 
     { 
     //this input was not an integer, we reset the stream to a good state and ignore the input 
     iss.clear(); 
     iss.ignore(numeric_limits<streamsize>::max(),' '); 
     } 
    } 
    cout << "Array contains:" << endl; 
    for (int i = 0 ; i < size ; i++) 
    { 
     cout << array[i] << ' ' << flush; 
    } 
    delete[] (array); 
    } 
} 

這裏是demonstration,你可以看到,輸入一行6 1 2 3 4 5 6

再次,我做了不是檢查一切,所以照顧你需要的方式。

編輯:錯誤閱讀後添加流的重置。

+0

非常好,乾淨。 – PSyLoCKe

+0

我看到'使用命名空間std',但我看不到'vector '; –

+1

如果OP想要一個帶有'vectors'的解決方案,我很樂意提供一個,但我認爲這看起來像是一個練習來理解動態分配,所以不會被允許。 – Djon