[英]Trying to create an output file with freopen, using non-constant string
我正在嘗試創建一個名稱為字符串常量,但由常量字符串“ List”組成的字符串,該字符串為整數+擴展名。 這是我的代碼:
#include <iostream>
#include <vector>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main (){
int cont=0;
std::string result;
std::string name = "Lista";
std::string ext = ".txt";
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", cont);
result = name + numstr+ext;
freopen (result, "w", stdout);
cout<<result<<endl;
return 0;
}
當我嘗試構建時會告訴我以下錯誤:
錯誤:無法將參數
1' to
std::string' to
轉換std::string' to
const char *'1' to
FILE * freopen(const char *,const char *,FILE *)'|
我該如何解決?
由於編譯器錯誤指出,沒有從std::string
到char const*
隱式轉換(即,在這種情況下為c樣式字符串 )。
盡管std::string
有一個名為c_str
的成員函數 ,它將生成一個以空值結尾的字符串,並返回一個指向它的指針,這在處理舊版C函數時非常有用。
freopen (result.c_str (), "w", stdout);
char const * p = result.c_str ();
請注意,如果您對托管對象進行任何修改(在本例中為result
),則std::string::c_str
指向的c-style-string將無效,因此,通常不明智的做法是將返回的值存儲在非臨時變量。
如果您點擊以下鏈接,則可以閱讀有關該功能的更多信息 :
我有一個完全可以做到這一點的小應用程序 。 有幾種方法可以做到這一點。其中最簡單的方法是
const char * newvar = stringname.c_str();
如果要使用sprintf
,則可能最容易跳過使用std::string
的操作:
char name[32];
sprintf(name, "lista%d.txt", cont);
freopen(name, "w", stdout);
如果要使用std::string
(無論如何,對於大多數C ++來說可能更可取),則可能要使用std::stringstream
創建名稱:
std::ostringstream name;
name << "lista" << cont << ".txt";
freopen(name.str().c_str(), "w", stdout);
但是,我通常傾向於避免使用freopen
, 並避免在C ++中使用C樣式的流(例如stout)。 通常最好寫一個ostream
。 上一個問題的答案顯示了如果確實需要,如何將cout
連接到另一個輸出文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.