user1448260
user1448260

Reputation: 263

Output to file c++

very simple program, not sure why it isn't working:

#include <iostream>
#include <fstream>
#include <stdio.h>

using namespace std;

int main ()

{
ofstream myfile ("test.txt");
if (myfile.is_open()) 
{
    for(  int i = 1;  i < 65535;  i++  )

     {
     myfile << ( "<connection> remote 208.211.39.160 %d udp </connection>\n", i );
     }
    myfile.close();
}
  return 0;
}

Basically it should print that sentence 65535 times, and then save it to a txt file. But the txt file just has a list of numbers from 1 to 65535, no words or formatting. Any ideas? Thanks for help.

Upvotes: 0

Views: 3621

Answers (5)

werupokz
werupokz

Reputation: 796

Try the following:

myfile << "<connection> remote 208.211.39.160 %d udp </connection>\n" << i;

Basically, myfile << (str , i) means "evaluate (str , i) and write the result of evaluation to ostream myfile".

The result of ( "<connection> remote 208.211.39.160 %d udp </connection>\n", i ) evaluation is equal to i

Take a look to comma operator description: http://en.wikipedia.org/wiki/Comma_operator

Upvotes: 1

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39390

If you want to concatenate the output, just pipe your data into two << operators, as such:

myfile << "<connection> remote 208.211.39.160 %d udp </connection>\n" << i;

Note that interpolation does not work in that case, so if you want to put your i variable into the middle of the string, you have to either split it by hand:

myfile << "<connection> remote 208.211.39.160 " << i << " udp </connection>\n"

Or apply some sort of other interpolation formatting before outputting it.

The problem

The problem exists in your code because in C++, (a, b) (the comma operator) returns b. So, in your code it meant you just wrote i to a file.

Upvotes: 5

Russ Freeman
Russ Freeman

Reputation: 1580

Looks like you are trying to "printf" and stream...

I think this is more like what you want:

myfile << "<connection> remote 208.211.39.160 " << i << " udp </connection>"<<std::endl;

Upvotes: 0

Karthik T
Karthik T

Reputation: 31962

You are using printf syntax to write using ofstream. Others have explained why it doesnt work. To fix it do the following

myfile << "<connection> remote 208.211.39.160"<<i<<"udp </connection>\n";

or if you want to go C style

printf( "<connection> remote 208.211.39.160 %d udp </connection>\n", i ); //fprintf to write to file

Upvotes: 0

billz
billz

Reputation: 45450

change

myfile << ( "<connection> remote 208.211.39.160 %d udp </connection>\n", i );

to

myfile << "<connection> remote 208.211.39.160 " << i << " udp </connection>\n";

Upvotes: 1

Related Questions