【发布时间】:2017-05-20 22:27:20
【问题描述】:
我在使用“C++ 编程原理和实践”中学习的一段特定代码时遇到了困难。
我无法从引用向量的循环中获得输出。我正在使用 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;
}
还是什么都没有。
在尝试了一些事情之后,通过消除,我很确定问题出在循环到向量的通信上,因为所有这些都可以正常工作:
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();
}
请问我错过了什么?提前谢谢你。
【问题讨论】:
-
您的代码工作正常。 wandbox.org/permlink/GYEiNuoMGABLZJpD 尝试使用
std::cout << std::endl而不是"\n"来刷新标准输出。 -
对不起,我是新手。我应该把它放在代码的什么地方?
-
您需要发出文件结束信号才能退出
for循环。在 Windows 的行首输入^Z然后输入。在 Linux 上键入^D。或者使用文件并重定向输入,EOF 将在文件的实际末尾触发。 -
我尝试了 ^Z 输入,但仍然没有。我不知道如何进行重定向。我正在使用这本书来学习 C++。对不起。但是感谢您的帮助。
-
^Z我的意思是Ctrl-Z,以防不明白。