I want to create a std::ifstream using std::string

A

Assertor

Hi, all.

Is there any way to create an instance of std::ifstream using
std::string.
(through std::ifstream's constructor or assignment operator or
iterator, etc...)

i.e.
std::string str = "this is a string";
std::ifstream ifs = str; //<----- this is a just pseudo code.

(^^;; I can solve this using making temporty file and write the str on
the file and reading it using std::ifstream...
but I don't want to make a additional file io ^^)

plz show me the way~
 
A

Alf P. Steinbach

* Assertor:
Is there any way to create an instance of std::ifstream using
std::string.
(through std::ifstream's constructor or assignment operator or
iterator, etc...)

i.e.
std::string str = "this is a string";
std::ifstream ifs = str; //<----- this is a just pseudo code.

(^^;; I can solve this using making temporty file and write the str on
the file and reading it using std::ifstream...
but I don't want to make a additional file io ^^)

Why don't you use a std::istringstream.
 
Z

Zeppe

how about this follow?

std::string str = "this is a string";
std::ifstream ifs(str.c_str());

this is a bad error, because in this case str is taken as a filename.

Regards,

Zeppe
 
J

James Kanze

Is there any way to create an instance of std::ifstream using
std::string.
(through std::ifstream's constructor or assignment operator or
iterator, etc...)
i.e.
std::string str = "this is a string";
std::ifstream ifs = str; //<----- this is a just pseudo code.
(^^;; I can solve this using making temporty file and write the str on
the file and reading it using std::ifstream...
but I don't want to make a additional file io ^^)

Why do you want to do this? Normally, except for creation, you
should be using the istream interface (from the base class).
And of course, this works just as well with an istringstream as
with an ifstream.
 
B

BobR

Zeppe wrote in message...
this is a bad error, because in this case str is taken as a filename.
Regards,
Zeppe

{
std::string str = "\"this is a string\"";
std::ifstream ifs( str.c_str() );
ifs << str << std::endl;
}

There! All fixed.
<G>

note: On some systems you need to put the filename in quotes if there are
spaces in the filename.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top