![](/img/trans.png)
[英]A general question about possible future C++ language or standard library features regarding bit streams
[英]regarding streams in c++
我想使用文件流和consol輸出流。 在構造函數中,我想根據傳遞給構造函數的參數使用文件或consol輸出流進行初始化。 然后,我將在類中具有另一個函數,該函數會將輸出重定向到該流。 它的代碼是什么? 我正在嘗試下面的代碼不起作用。 任何其他設計建議均受到歡迎。
class Test
{
private:
std::ios *obj;
std::ofstream file;
std::ostream cout1;
public:
// Test(){}
Test(char choice[])
{
if(choice=="file")
{
obj=new ofstream();
obj->open("temp.txt");
}
else
obj=new ostream();
}
void printarray()
{
for(int i=0;i<5;i++)
(*obj)<<"\n \n"<<"HI"
}
};
這樣的事情應該起作用:
#include <iostream>
#include <fstream>
#include <string>
class Test
{
private:
std::ofstream file;
std::ostream& obj;
public:
// Use overloaded constructors. When the default constructor is used,
// use std::cout. When the constructor with string is used, use the argument
// as the file to write to.
Test() : obj(std::cout) {}
Test(std::string const& f) : file(f.c_str()), obj(file) {}
void printarray()
{
for(int i=0;i<5;i++)
obj<<"\n " << "HI" << " \n";
}
};
int main()
{
Test a;
a.printarray();
Test b("out.txt");
b.printarray();
}
PS查看對printarray
的更改。 您嘗試使用%s
進行的操作對printf
系列函數很有用,但對std::ostream
沒有幫助。
任何其他設計建議均受到歡迎。
這些成員中有兩個是無用的:
std::ios *obj;
std::ofstream file;
std::ostream cout1;
使用std::ios
和與streambuf
無關的std::ostream
不能執行任何操作,而且您也永遠不會使用file
或cout1
!
你要:
std::ofstream file;
std::ostream& out;
如圖中的R薩胡的回答,並寫out
。
Test(char choice[])
{
if(choice=="file")
這不起作用,您需要使用strcmp
來比較char
字符串。 您可能應該使用std::string
而不是char*
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.