2015-12-03 19 views
2

是否有可能實現類似這樣的事情?可以通過從std :: cin中提取來初始化變量嗎?

cin >> int num; 

這樣做的原因是因爲我正在嘗試讀取循環sentinel值的標準輸入流。當前的代碼是:

int num; 
for (cin >> num; num > 0; --num) {...} 

如果我能實現我所要求的,NUM可以從從未使用它的外部範圍中刪除,限制了它的for循環,從而節省內存僅有不到。

+0

@ user657267你會在每次迭代時調用cin。我只需要在循環開始之前調用它一次。 – thegreatjedi

+0

@ M.M,我會在哪裏放置cin語句?我只需要調用cin來初始化num一次,所以我不能將它完全放入循環中。 – thegreatjedi

+0

@M.M不會被稱爲每次迭代? – thegreatjedi

回答

0

cin >> num只是語法糖cin.operator>>(num)這可能是cin.foo(num)。所以我們只是稱它爲foo(num)。沒有你基本上是說你想使用:

void foo(int& arg) { 
    cin >> arg; 
} 
// ... 
foo(int i); 

定義iint並初始化爲一些用戶輸入。目前不是C++。我也不會想到。

1

我的意思是,如果這只是內聯初始化,那麼你可以使用istream_iterator來實現這一點。

for(int i = *istream_iterator<int>(cin); i > 0; --i) 

[Live Example]

這會失敗,就像壯觀的cin >> i想,如果你比從標準輸入的int其他的東西閱讀。請記住,你犧牲錯誤檢查一行初始化。更好的方法可能是寫各種各樣的重複提示:

int readInt(){ 
    int result; 

    cout << "Please input a number: "; 

     while(!(cin >> result)){ 
     cin.clear(); 
     cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
     cout << "Error\nPlease input a number: "; 
    } 
    return result; 
} 

然後,只需調用:

for(int i = readInt(); i > 0; --i) 
+0

'cin >> i'在抽取失敗的情況下是明確定義的。 –

+0

@ M.M。這是真的,因爲C++ 11('i'保證在失敗後是0) –

+0

@ M.M我知道這是定義的,我只是不認爲將無效輸入翻譯爲0將是所需的行爲。 –

2

這裏有一些選擇:


{ 
    int num = 0; 
    for (cin >> num; num > 0; --num) {...} 
} 

for (int num = 0, unused = !(cin >> num); num > 0; --num) { ... } 

感謝TonyD這一個:

for (int num = (cin >> num ? num : 0); num > 0; --num) { ... } 

int read_int() { int x = 0; cin >> x; return x; } 

// ... 

for (int num = read_int(); num > 0; --num) { ... } 

for (int num = [](){ int x = 0; cin >> x; return x; }(); num > 0; --num) { ... } 

NB。這些版本在讀取失敗的情況下跳過循環。你可能希望拋出異常,或者其他的東西。

+0

關於[coliru](http://coliru.stacked-crooked.com/a/6024530731aec8ff),'unused = cin >> num'版本給出'錯誤:無效的用戶自定義轉換'std :: basic_istream : :__ istream_type {aka std :: basic_istream }'爲'int',因爲候選轉換是':: operator void *()const',並且沒有已知的從'void *'轉換爲'int'的轉換。似乎GCC的標準庫已經轉移到'iostream :: operator bool()const',但希望能夠解決這個問題。 –

+0

@TonyD固定。我承認我沒有嘗試過。問題在於'operator bool'是'explicit'。 –

+0

FWIW,'int num =(cin >> num,num);'似乎也可以工作,儘管即使操作符是序列點也是合法的(我不是100%確定的),它會關注代碼的足夠的評論者並浪費他們的時間,這是不值得實際使用的。 –