sách gpt4 ăn đã đi

c++ - 使用 C++ 的原则和实践,如何退出循环

In lại 作者:太空狗 更新时间:2023-10-29 20:52:11 25 4
mua khóa gpt4 giày nike

我是初学者,我正在使用“编程:使用 C++ 的原则和实践”学习 C++,作为引用,我在第 4 章,我对 4.6.3 和 4.6.4 的示例有一些疑问,我将粘贴部分代码,然后解释让我困惑的地方,它可能非常基本:

int chính()
{
vector 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 上使用 Microsoft Visual Studio 2017,如果我运行上面的代码,我可以继续输入单词,但我不知道如何“退出”for 循环并到达“cout”部分。第 4 章这两个部分中的所有示例都有这个问题(对我来说),一旦我运行这些代码,我就会陷入 for 循环,就是这样,现在我知道我可以使用 and if 语句并决定使用特定字符,比如 0,退出循环并运行其余代码,但作者没有这样做,这告诉我可能有一些快捷键可以在不关闭程序的情况下“退出”循环。

câu trả lời hay nhất

一旦完成输入字符串,按 Enter 然后按 Điều khiển + VỚI 如果在 Windows 或 Điều khiển + D 如果在 Linux 上紧接着另一个 Enter。这会将 EOF 字符发送到您的输入流,导致 cin >> temp; 条件(隐式)评估为 SAI 从而退出 for loop .以上可以转换为使用trong khi循环:

#include 
#include
#include

int chính() {
char c = 'y';
std::string tempstr;
std::vector 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();
}
}

关于c++ - 使用 C++ 的原则和实践,如何退出循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46685186/

25 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress