Jcrack
Jcrack

Reputation: 289

fscanf type function for streams?

I'm used to using fscanf for simple file input, because it makes it simple. I'm trying to move to streams though and I'd like to be able to do this:

fscanf(file, %d %s, int1, str1);

as you can see it's relatively easy to read through a file, stick the first int you come across into one container, and then the first string into a char*. What I want, is to do this with fstreams, using stream functions. This is what I came up with, with my limited stream knowledge.

while((fGet = File.get() != EOF))
{
    int x;
    int y;
    bool oscillate = false;
    switch(oscillate)
    {
    case false:
        {
            x = fGet;
            oscillate = true;
            break;
        }
    case true:
        {
            y = fGet;
            oscillate = false;
            break;
        }
    }
}

Basically I want to scan through a file and put the first int into x, and the second into y.

This is pretty bad for a few reasons, as you can tell, and I'd never actually use this but it's all I can think of. Is there a better way to go about this?

Upvotes: 1

Views: 1969

Answers (1)

Seth Carnegie
Seth Carnegie

Reputation: 75130

To read two integers from a stream, all you have to do is

int x, y;
File >> x >> y;

And the equivalent of

fscanf(file, "%d %s", &int1, str1);

Is

int x;
string s;

file >> x >> s;

And make sure that if you want to check whether the reads worked, put the reads in the condition:

if (file >> x >> s)

or

while (file >> x >> y)

or whatever.

Upvotes: 5

Related Questions