一 std::endl 等于三 std::endl(s)?

One std::endl makes three std::endl(s)?

我想为一个更大的程序编写一个小的命令行解释器示例。但是如果我输入“1 2 3”,输出是“1\n2\n3\n”而不是我期望的“1 2 3\n”。

#include <iostream>

int main(int argc, char **argv) {
    while (true) {
        std::string line;
        std::cin >> line;
        std::cout << line << std::endl;
    }

    return 0;
}

您应该试试 getline 函数。 getline 将提供您预期的输出

#include <iostream>

int main(int argc, char **argv) {
    while (true) {
        std::string line;
        std::getline (std::cin,  line);
        std::cout << line << std::endl;
    }

    return 0;
}