[英]principles and practice using C++, how to exit a loop
I'm a beginner and I'm studying c++ using "Programming: principles and practice using C++, for reference I'm at chapter 4 and I have some doubts on the example at 4.6.3 and 4.6.4, I'm gonna paste part of a code and then explaing what puzzles me, it's likely very basic: 我是初学者,我正在学习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';
}
now I'm on windows 7 and I am using microsoft visual studio 2017, if I run the above code I can keep on entering words but I don't know how to "exit" the for loop and arrive to the "cout" part. 现在我在Windows 7上,我正在使用微软视觉工作室2017,如果我运行上面的代码我可以继续输入单词,但我不知道如何“退出”for循环并到达“cout”部分。 All the examples in these 2 sections of chapter 4 have that problem (for me), once I run these codes I get stuck in the for loop and that's it, now I know I could use and if statement and decide to use a particular character, say 0, to exit the loop and run the rest of the code, but the author does not and that tells me that there might be some shortkey to "exit" the loop without closing the program.
第4章的这两个部分中的所有示例都有这个问题(对我来说),一旦我运行这些代码,我就会陷入for循环,就是这样,现在我知道我可以使用if语句并决定使用特定的字符,比方说0,退出循环并运行其余代码,但作者没有,这告诉我可能有一些短键“退出”循环而不关闭程序。
Once done entering strings, press Enter and then press Ctrl + Z if on Windows or Ctrl + D if on Linux followed by yet another Enter . 完成输入字符串后,按Enter键 ,然后按Ctrl + Z(如果在Windows上)或Ctrl + D(如果在Linux上),然后再按Enter键 。 That will send the EOF character to your input stream causing the
cin >> temp;
这会将EOF字符发送到输入流,导致
cin >> temp;
condition to (implicitly) evaluate to false
thus exiting the for loop . 条件到(隐式)求值为
false
从而退出for循环 。 The above can be converted to use the while loop: 以上可以转换为使用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.