2013-03-08 45 views
1

在這個問題中我面臨一個問題: 「編寫一個C++控制檯程序來接受來自鍵盤的五個整數值,並用空格分隔。使用指針將這五個值存儲在一個數組中,然後在屏幕上打印數組的元素。「C++程序接受多個輸入並使用指針輸入數組

我試着做一個字符串變量,並接受來自用戶的5個整數,然後將其轉換爲整數,但它不能很好地工作,因爲它不會在空間之後採用數字。

任何幫助傢伙?

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

using namespace std; 

int main(){ 
    string numbers; 
    getline(cin, numbers); 
    int arr[5]; 
    int *ptr; 
    int values; 
    stringstream convert(numbers); 
    convert >> values; 
    cout << values; 


} 
+0

我會親自用字符串流獲得的每一整數及使用類似'* PTR = thatInt;'納入指針。 – chris 2013-03-08 18:34:10

回答

0

這將只需要一次一個,你需要添加更多的調用,像這樣轉換:

stringstream convert(numbers); 
    convert >> values; 
    cout << values; 
    convert >> values; 
    cout << " " << values; 
    convert >> values; 
    cout << " " << values; 

C++的常見問題有一個很好的section

如果沒有大的修改,如果你需要直接使用指針把號碼存入數組,你可以這樣做:

int *ptr = arr ; 

convert >> *ptr++ ; 
convert >> *ptr++; 
convert >> *ptr++; 
convert >> *ptr++; 
convert >> *ptr++; 

for(unsigned int i = 0; i < 5; ++i) 
{ 
    cout << arr[i] << " " ; 
} 
cout << std::endl ; 
+0

但我需要把它放在一個數組中,使用指針 – 2013-03-08 18:54:54

+0

@AhmedSherif添加代碼以使用指針插入到數組中 – 2013-03-08 19:03:14

0

我的數字變量是字符串,則可以使用搜索第一個非空格字符numbers.find_first_not_of(" ");
和第一個空格字符numbers.find_first_of(" ");
然後使用substr(.....)
創建一個子集現在將substr放在另一個字符串變量中。
現在將子字符串轉換爲int。
重複您需要的次數的步驟。即將整個代碼放在while循環中。
終止循環,只要numbers.find_first_of(" ");回報numbers.end()

+0

對不起,我不能很好地解釋它,你能用代碼解釋它嗎? – 2013-03-08 18:50:23

0

我成功地使它

#include<iostream> 
#include<string> 
#include<sstream> 
using namespace std; 

int main(){ 
int arr[5]; 
string number; 
cout << "Please enter 5 integers separeted with spaces " << endl; 
getline(cin, number); 
int *ptr = arr ; 
stringstream convert(number); 
convert >> *ptr++ ; 
convert >> *ptr++; 
convert >> *ptr++; 
convert >> *ptr++; 
convert >> *ptr++; 

for( int i = 0; i < 5; ++i) 
{ 
    cout << arr[i] << " " ; 
} 
cout << std::endl ; 
}