2014-03-28 134 views
3

好傢伙遇到麻煩試圖實現進入我的計劃的重要組成部分,當停止輸入值,數組按下回車鍵

int list[50]; 
int i = 0; 
while (/*enter key has not been pressed*/&& i < 50){ 
    cin>>list[i]; 
    i++; 
    } 

如何它應該工作,將採取由分開的整數空格並將它們存儲到數組中。當輸入鍵被按下時,它應該停止接受輸入。

PS我發佈這從我的手機,這就是爲什麼我無法正確格式化文本。如果語法有任何問題,可能會忽略它,因爲我只關注「回車鍵」部分。

回答

2

你可以使用一個字符串流,基本上你將整行讀入一個字符串,然後你開始從該字符串讀取整數到你的數組中。
讀字符串將終止,當你按下回車鍵,所以我認爲這工作爲你

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

using namespace :: std; // bad idea, I am just lazy to type "std" so much 
int main(){ 


    const int arrSize = 5; 

    int arr [arrSize] = {0}; //initialize arr zeros 
    string line; 
    getline(cin,line); 


    cout <<"you entered " << line<<endl; // just to check the string you entered 
    stringstream ss (line); 

    int i = 0; 
    while (ss>>arr[i++] && i < arrSize); // this might look a bit ugly 


    for (int i =0; i < arrSize; i++) // checking the content of the list 
     cout<<arr[i]<<" "; 

    getchar(); 


    return 0; 



} 

注意,不測試從用戶(如字母而不是數字)輸入錯誤。

+0

我相信你需要'#include '爲該代碼編譯,由於調用'getchar()' – Alejandro

+0

我試過VS 2012上的代碼,它工作,我猜'cstdio'通過'' –

+0

以某種方式間接包含是讀取一行數組的最佳方式 –

0

這裏的關鍵是使用break關鍵字。

int list[50]; 
int i = 0; 
int input; 
while (i < 50){ 
    cin >> input; 
    if(input == '\n') break; 
    list[i] = input; 
    i++; 
} 

即時猜測你是新來proramming,所以比較的intchar似乎有點怪你。基本上,所有chars也是ASCII形式的ints。

+0

如果要插入'10',這是新行的ASCII碼值 –

+0

@ Mhd.Tahawi那麼你被綁定了:P10無論如何都是這樣一個無聊的數字,你爲什麼要這麼做?在所有嚴峻的事情中,這是一個好點,我不確定。你可能需要rearchitechture這個接受字符串,然後檢查字符串格式的10或換行 –

+0

是啊傻我,想着10號:P –