简体   繁体   中英

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:

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. 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.

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 . That will send the EOF character to your input stream causing the cin >> temp; condition to (implicitly) evaluate to false thus exiting the for loop . The above can be converted to use the while loop:

#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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM