[英]Output to file 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++ )
{
myfile << ( "<connection> remote 208.211.39.160 %d udp </connection>\n", i );
}
myfile.close();
}
return 0;
}
基本上,它应该打印该语句65535次,然后将其保存到txt文件中。 但是txt文件仅包含从1到65535的数字列表,没有单词或格式。 有任何想法吗? 感谢帮助。
如果要连接输出,只需将数据通过管道传送到两个<<
操作符,如下所示:
myfile << "<connection> remote 208.211.39.160 %d udp </connection>\n" << i;
请注意,插值在这种情况下不起作用,因此,如果要将i
变量放入字符串的中间,则必须手动将其拆分:
myfile << "<connection> remote 208.211.39.160 " << i << " udp </connection>\n"
或在输出之前应用某种其他插值格式。
该问题存在于您的代码中,因为在C ++中, (a, b)
(逗号运算符)返回b
。 因此,在您的代码中,这意味着您只是将i
写入了文件。
更改
myfile << ( "<connection> remote 208.211.39.160 %d udp </connection>\n", i );
至
myfile << "<connection> remote 208.211.39.160 " << i << " udp </connection>\n";
请尝试以下操作:
myfile << "<connection> remote 208.211.39.160 %d udp </connection>\n" << i;
基本上, myfile << (str , i)
意思是“ 评估(str , i)
并将评估结果写入ostream myfile ”。
( "<connection> remote 208.211.39.160 %d udp </connection>\\n", i )
结果等于i
看一下逗号运算符的描述: http : //en.wikipedia.org/wiki/Comma_operator
您正在使用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 " << i << " udp </connection>"<<std::endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.