输出到文件C++

输出到文件C++,c++,C++,非常简单的程序,不确定为什么不起作用: #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++ ) { myfi

非常简单的程序,不确定为什么不起作用:

#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;
}

基本上,它应该将这个句子打印65535次,然后保存到一个txt文件中。但是txt文件只有一个从1到65535的数字列表,没有单词或格式。有什么想法吗?谢谢您的帮助。

如果您想连接输出,只需将数据分成两部分即可


您正在使用printf语法来使用ofstream进行编写。其他人解释了为什么它不起作用。要修复它,请执行以下操作

myfile << "<connection> remote 208.211.39.160"<<i<<"udp </connection>\n";
或者如果你想走C风格

printf( "<connection> remote 208.211.39.160 %d udp </connection>\n", i ); //fprintf to write to file
请尝试以下操作:

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

基本上,myfile看起来像是在尝试打印F和流式处理

我认为这更像是你想要的:

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

逗号运算符:谁知道什么时候会引起混乱!阅读这里逗号运算符的用法。感谢它现在可以工作了,但是我犯了一个错误,我最多只能有64个数字,它们需要在10001和65535之间随机。有人知道吗?没有,当然没有。我补充了一点来澄清这一点。如果他打开了fstream,他应该如何使用fprintf?我理解sprintf的建议。@BartekBanachewicz很抱歉没有更好地解释,C风格也意味着fopen/fclose。
myfile << "<connection> remote 208.211.39.160"<<i<<"udp </connection>\n";
printf( "<connection> remote 208.211.39.160 %d udp </connection>\n", i ); //fprintf to write to file
myfile << "<connection> remote 208.211.39.160 %d udp </connection>\n" << i;
myfile << "<connection> remote 208.211.39.160 " << i << " udp </connection>"<<std::endl;