作者holder319 (大頭)
看板NCTU-STAT94G
標題Re: [心得] fprintf 改檔名自動輸出
時間Fri Oct 27 11:51:07 2006
※ 引述《catherinejoy (whatcanisay)》之銘言:
若你把副檔名改成.cpp,然後在開頭 include "iostream" "fstream" "cstring",
那下面的code會更簡潔,輸出輸入也不再需要手動設定格式,一切有預設值自動化.
(當然,做文字處理時你也可以include "string" 然後跟 "cstring" 交叉轉換使用)
ex:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void main()
{
string str; //也可事先在此指定 string str = "../123/abc.txt" (相對路徑)
cout<<"input path and filename \n";
cin>>str; // 輸入檔名與要輸出路徑,路徑預設值是目前資料夾
// 因為每個人的電腦系統不一樣,故用相對路徑會比絕對路徑好
ofstream ofile(str.c_str()); // 建立要輸出的檔案
ofile<<"\n a.xxx = "<<123 // 輸出東西到檔案
<<"\n b.yyy = "<<456.789
<<"\n ";
ofile.close();
}
: main 裡
: //export_txt('D:/2006_fall/NHRI','delA',ans,del,item);
: printf("Please input the FILE NAME:\n");
: scanf("%s",&filename);//輸入檔名開頭
: for(i=0;i<del;i++){
: sprintf(filename,"%s_%d",filename,i);//filename_i.txt
: //path="D:/2006_fall/NHRI/i";
: sprintf(path,"%s/%d","D:/2006_fall/NHRI",i);//也可以改路徑
: export_txt(path,filename,ans,del,item);
: printf("\n%s.txt is OK!!!\n",filename);
: }//end for i
: header
: void export_txt(char *path,char *FileName,double **ans,int nrow, int ncol){
: char Name[1024];
: int i,j;
: sprintf(Name,"%s/%s.txt",path,FileName);
: out = fopen(Name,"w");
: for(i=0;i<nrow;i++){
: fprintf(out,"%d\t",i+1);
: for(j=0;j<ncol;j++){
: fprintf(out,"%3.0lf\t",ans[i][j]);
: }//end for j
: fprintf(out,"\n");
: }//end for i
: }
: 好 請享用...
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.113.212.111
※ 編輯: holder319 來自: 140.113.212.111 (10/27 11:52)
※ 編輯: holder319 來自: 140.113.114.85 (10/28 02:27)
※ 編輯: holder319 來自: 140.113.114.85 (10/28 02:30)
1F:推 catherinejoy:大力推.... 10/29 21:00