当给定一个字符串时,Cout 在行首开始打印

Cout starts printing at start of line when given a string

我在 C++ 中有一个字符串向量,名为 lines

这一行

std::cout << "First line: >" << lines[0] << "<" << std::endl; 

打印“>第一行:>string_here”而不是 "First line: >string_here<"。

为什么cout会在字符串后的当前行的开头开始打印,如何解决?我也尝试在每次 cout 后冲洗,但结果是一样的。

这是说明我的问题的完整代码,在解决之前

#include <iostream>
#include <vector>
#include <string.h>

std::vector<std::string> parse(char *buffer, const char *delimiter) {
    std::string buff(buffer);
    size_t pos = 0;
    std::string part;
    std::vector<std::string> parts;
    while ((pos = buff.find(delimiter)) != std::string::npos) {
        part = buff.substr(0, pos);
        parts.push_back(part);
        buff.erase(0, pos + 1);
    }

    parts.push_back(buff);

    return parts;
}

int main() {
    char *s;
    s = strdup("Many lines\r\nOf text");

    std::cout << s << std::endl;  // this should print the string how it is

    std::vector<std::string> lines;
    lines = parse(s, "\n");  // parsing the string, after "\n" delimiter
    // that was the problem, I should have parsed after "\r\n"

    std::cout << "First line: >"<< lines[0] << "<" << std::endl;  // output
}

如果没有 lines[0] 的全部内容是不可能确定的,但我(有根据的)猜测是 lines[0]\r 结尾,回车符 return字符,所以在 lines[0] 之后打印的所有内容都打印在行的开头。