![](/img/trans.png)
[英]Programming Principles and Practice using C++ while-loop drill. Can't find a way to exit the loop
[英]principles and practice using C++, how to exit a loop
我是初學者,我正在學習c ++使用“編程:使用C ++的原理和練習,作為參考我在第4章,我對4.6.3和4.6.4的例子有一些疑問,我要去粘貼代碼的一部分,然后解釋困惑我的東西,它可能是非常基本的:
int main()
{
vector<string> words;
for (string temp; cin >> temp; ) // read whitespace-separated words
words.push_back(temp); // put into vector
cout << "Number of words: " << words.size() << '\n';
}
現在我在Windows 7上,我正在使用微軟視覺工作室2017,如果我運行上面的代碼我可以繼續輸入單詞,但我不知道如何“退出”for循環並到達“cout”部分。 第4章的這兩個部分中的所有示例都有這個問題(對我來說),一旦我運行這些代碼,我就會陷入for循環,就是這樣,現在我知道我可以使用if語句並決定使用特定的字符,比方說0,退出循環並運行其余代碼,但作者沒有,這告訴我可能有一些短鍵“退出”循環而不關閉程序。
完成輸入字符串后,按Enter鍵 ,然后按Ctrl + Z(如果在Windows上)或Ctrl + D(如果在Linux上),然后再按Enter鍵 。 這會將EOF字符發送到輸入流,導致cin >> temp;
條件到(隱式)求值為false
從而退出for循環 。 以上可以轉換為使用while循環:
#include <iostream>
#include <vector>
#include <string>
int main() {
char c = 'y';
std::string tempstr;
std::vector<std::string> words;
while (std::cin && c == 'y'){
std::cout << "Enter string: " << std::endl;
std::getline(std::cin, tempstr);
words.push_back(tempstr);
std::cout << "Another entry? y/n: ";
std::cin >> c;
std::cin.ignore();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.