我试图穿越并输出向量,但是除了要求我输入之外,没有其他事情发生。
int main() {
string a;
vector<string> test;
while (std::cin>>a) {
test.push_back(a);
}
for (vector<string>::iterator i= test.begin(); i!= test.end(); ++i) {
std::cout << *i << std::endl;
}
system("pause");
return 0;
}
std::cin >> a
将跳过所有空格,并且只会将非空格字符放入字符串中。这意味着,即使您只按Enter,a
也永远不会空。因此,即使对a.empty()
进行检查也不会对您不好。循环将继续进行,直到您的I/O环境出现问题(即实际上永远不会(,或者您因为向量太大而用完了记忆,在这种情况下,循环是通过例外撤离的。
您需要做的是致电std::getline
。该功能读取了一整行输入,并在新线后停止,而不是完全无视新线。然后,您可以检查empty()
以查看是否输入。这是一个示例:
#include <iostream>
#include <string>
#include <vector>
int main() {
std::string a;
std::vector<std::string> test;
while (std::getline(std::cin, a) && !a.empty()) {
test.push_back(a);
}
for (auto const& s : test) {
std::cout << s << 'n';
}
}
我还简化了代码,并自由向您展示using namespace std;
和system("pause")
是坏主意。