C ++没有显示cout信息

时间:2017-05-01 09:33:04

标签: c++

我试图遍历并输出向量,但除了要求输入之外没有任何其他事情发生。

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;
}

1 个答案:

答案 0 :(得分:1)

std::cin >> a将跳过所有空格,并且只会将非空格字符放入字符串中。这意味着,除其他事项外,a永远不会为空,即使您只需按Enter键。因此即使检查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")是不好的主意。