gpt4 book ai didi

c++ - Bjarne Stroustrup Book - vector 和 For 循环 - 不起作用

转载 作者:可可西里 更新时间:2023-11-01 14:59:56 24 4
gpt4 key购买 nike

我在使用“使用 C++ 的编程原则和实践”学习的一段特定代码时遇到困难。

我无法从引用 vector 的循环中获得输出。我正在使用 std_lib_facilities 和 stdafx,因为这本书和 MVS 告诉我的。

#include "stdafx.h"
#include "../../std_lib_facilities.h"


int main()
{
vector<string>words;
for(string temp; cin>>temp; )
words.push_back(temp);
cout << "Number of words: " << words.size() << '\n';
}

这不会产生任何结果。我会得到提示,输入一些单词,然后输入,然后什么也没有。

尝试了我从这里和其他网站获得的一些变体,例如:

//here i tried the libraries the guy used in his code
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
cout << "Please enter a series of words followed by End-of-File: ";
vector<string> words;
string word;
string disliked = "Broccoli";

while (cin >> word)
words.push_back(word);

cout << "\nNumber of words: " << words.size() << endl;

// cycle through all strings in vector
for (int i = 0; i < words.size(); ++i)
{
if (words[i] != disliked)
cout << words[i] << endl;
else
cout << "BLEEP!\n";
}
return 0;
}

仍然没有。

在尝试了一些东西之后,通过消除我很确定问题出在循环到 vector 的通信上,因为所有这些都工作正常:

int main()
{
vector<string>words = { "hi" };
words.push_back("hello");
cout << words[1] << "\n"; // this will print hello

for (int i = 0; i < words.size();++i) {
cout << words[i] << "\n"; // this will print out all elements
// inside vector words, ( hi, hello)
}

cout << words.size();// this will print out number 2

for (string temp; cin >> temp;) {
words.push_back(temp);
}

cout << words.size();// this won't do anything after i type in some
// words; shouldn't it increase the size of the
// vector?
}

这也不会:

int main()
{
vector<string>words = { "hi" };
for (string temp; cin >> temp;) {
words.push_back(temp);
}
cout << words.size();
}

请问我错过了什么?提前谢谢你。

最佳答案

输入字符串,完成后按 Ctrl+Z(后跟 Enter)(如果在 Windows 上)或 Ctrl+D 如果在 Linux 上。当您这样做时,for 循环中的 cin>>temp; 条件将评估为 false,您的程序将退出循环。

关于c++ - Bjarne Stroustrup Book - vector 和 For 循环 - 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44091391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com