簡體   English   中英

輸出到文件C ++

[英]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_o​​perator

您正在使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM