简体   繁体   English

C ++打印向量添加新行

[英]C++ Printing Vector Adding New Line

I have a vector of structs. 我有一个结构向量。

struct myStruct{
string text;
int num;
};

vector<myStruct> foo;

And I am attempting to print the text followed by a space, then the number. 我正在尝试打印文本,后跟一个空格,然后是数字。 Like so: 像这样:

foobar 5 foob​​ar 5

But when trying to print my vector using 但是当尝试使用打印我的矢量时

ofstream outputFile;
outputFile.open ("file.txt");

for(int i = 0; i < foo.size(); i++) {
        outputFile << foo[x].text << " " << foo[x].num << endl;
    }

It prints like 它打印像

foobar  
 5 
moretext  
 8

With an extra newline and space. 带有额外的换行符和空间。 I can't figure out how to get rid of it and print it on the same line. 我不知道如何摆脱它,并在同一行上打印它。 Any suggestions? 有什么建议么?

您可以检查foo [x] .text是否包含\\ r或\\ n。

"I am using getline(input, foo.text). So it should discard the newline character" “我正在使用getline(input,foo.text)。因此它应该丢弃换行符”

std::getline() adds a carriage return at end , if your input stream has windows-style line-breaks (CRLF), and you're using a program on unix, which has LF 如果您的input流具有Windows样式的换行符(CRLF),并且您正在unix上使用LF的程序,则std::getline()在末尾添加回车符

You need to trim it, using some like : 您需要使用类似以下内容进行修整:

foo.text.erase(foo.text.find_last_not_of("\\n\\r")+1);

One hack would be merging the string before you pass it to outputFile. 一种技巧是在将字符串传递给outputFile之前合并该字符串。

or 要么

Have you tried playing around with the mode setting with open() method? 您是否尝试过使用open()方法处理模式设置? eg 例如

outputFile.open ("file.txt", std::ofstream::out | std::ofstream::app); outputFile.open(“ file.txt”,std :: ofstream :: out | std :: ofstream :: app);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM