简体   繁体   中英

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

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"

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

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.

or

Have you tried playing around with the mode setting with open() method? eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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