Tommy
Tommy

Reputation: 13672

use ifstream with a string instead of a file in c++?

ifstream has nice tools for parsing files, such as << which work in loops and can consume floats, ints, or whatever you want into variables (as long as your variable types match what you are trying to consume with <<. I want to know if, instead of:

ifstream myReadFile;
myReadFile.open(some_file); // open the file
float x;
int y;
// some_file = "0.5 5"
myReadFile >> x >> y;

If I can somehow get a string object that is identical to some_file into ifstream. What I want to do is:

ifstream myReadFile;
myReadFile = my_string
...

Essentially parsing files is easy with ifstreams but parsing strings in c++ is a PITA (compared to say, Python).

Upvotes: 0

Views: 776

Answers (2)

Mark Garcia
Mark Garcia

Reputation: 17708

Use std::stringstream:

// Initialize contents of the stream with your string
std::stringstream myReadString(my_string);  

float x;
int y;

// Use the stream just like an fstream
// my_string = "0.5 5"
myReadString >> x >> y;

Upvotes: 3

Aniket Inge
Aniket Inge

Reputation: 25723

erm, you might want to look at stringstream.

Upvotes: 0

Related Questions