【问题标题】:Cout starts printing at start of line when given a string给定字符串时,Cout 在行首开始打印
【发布时间】:2017-10-18 03:37:30
【问题描述】:

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

这一行

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

打印“>第一行:>string_here”而不是“第一行:>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
}

【问题讨论】:

  • 行[0]中有什么?
  • 你能在其他地方复制它吗?这似乎是系统特定的。
  • 那是另一件奇怪的事情,在行[0] 中有一个正好 31 个字符的字符串,但是当我打印它的长度时,它说 32。我检查了,最后一个不是 endline,只是空。
  • 我在 ubuntu 中尝试过,我可以在 30 分钟内尝试使用 ubuntu gnome
  • 请提供minimal reproducible example。仅从您在此处提供的代码来看,它没有理由产生您报告的输出

标签: c++ string std cout flush


【解决方案1】:

如果没有lines[0] 的全部内容,就无法确定,但我(受过教育的)猜测是lines[0] 以回车符\r 结尾,所以在lines[0] 之后打印的所有内容都打印为行首。

【讨论】:

  • 是的,这就是问题所在。我试图从一个有很多的字符串中逐行获取行,并且我在“\n”之后进行解析,而分隔符实际上是“\r\n”。我将提供一个完整的代码来完全显示问题
  • @VladIordache 即使有\r 之类的,我认为你不能在输出中有两个&gt;
  • 第一个>是
猜你喜欢
  • 2020-06-16
  • 1970-01-01
  • 1970-01-01
  • 2019-01-11
  • 2020-11-08
  • 2021-10-12
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多