I have a vector of strings in C++, named lines
.
This line
std::cout << "First line: >" << lines[0] << "<" << std::endl;
prints ">irst line: >string_here" instead of "First line: >string_here<".
Why does cout start printing at the start of the current line after the string, and how can I resolve it? I also tried to flush after every cout but result was the same.
This is a full code that ilustrates my problem, BEFORE it was solved:
#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
}
It's impossible to be sure without the full content of lines[0]
, but my (educated) guess would be that lines[0]
ends with \r
, the carriage return character, so everything printed after lines[0]
is printed a the beginning of the line.