stdoutstdinendl

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


I want to code a small command line interpreter example for a bigger program. But if I enter "1 2 3" the output is "1\n2\n3\n" and not "1 2 3\n" as I would expect.

#include <iostream>

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

    return 0;
}

Solution

  • you should try getline function . getline will deliver your expected output

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