0

非常简单的程序,不知道为什么它不工作:

#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 的数字列表,没有文字或格式。有任何想法吗?感谢帮助。

4

5 回答 5

5

如果要连接输出,只需将数据通过管道传输到两个<<运算符,如下所示:

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了一个文件。

于 2012-12-14T08:44:24.630 回答
1

尝试以下操作:

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_o​​perator

于 2012-12-14T08:46:42.617 回答
1

改变

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

myfile << "<connection> remote 208.211.39.160 " << i << " udp </connection>\n";
于 2012-12-14T08:45:58.210 回答
0

看起来您正在尝试“printf”并流式传输...

我认为这更像你想要的:

myfile << "<connection> remote 208.211.39.160 " << i << " udp </connection>"<<std::endl;
于 2012-12-14T08:47:03.990 回答
0

您正在使用 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
于 2012-12-14T08:46:17.417 回答