【发布时间】: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。仅从您在此处提供的代码来看,它没有理由产生您报告的输出