basic C++ <iostream> question

Posts: 321
Joined: 2004.10
Post: #1
This is probably so simple or basic that all my books and web searches have turned up nothing..but

Can the cin be redirected from the keyboard to some arbitrary data file?

I've got code which uses <istream> and cin, but has data files. To me
as soon as I see data files, I think <ifstream>. And as soon as I see <istream>
I think of typing data at the terminal and entering return.

But the code (not my own) I'm studying has the following:

int main()
    // read and store the data
    while (cin >> ch) {
        if (ch == 'U')
            record = new Core;      // allocate a `Core' object
            record = new Grad;      // allocate a `Grad' object

but a data file like:

G Moo 100 100 100 100 100 100 100 100 100
U Moore 75 85 77 59 0 85 75 89
G Norman 57 78 73 66 78 70 88 89 84

So seems to me, their must be a way to seat cin to the data file and NOT the keyboard.
Quote this message in a reply
Posts: 1,403
Joined: 2005.07
Post: #2
this doesn't answer your question but you can use an ifstream in a very similar way to cin, like so:

#include <string>
#include <fstream>
#include <iostream>

Track::Track(std::string file_name)
    float x, y, z;
    wire_vertex w;
    std::ifstream inFile(file_name.c_str(), std::ios::in);        // relevant
    wire = new Array<wire_vertex>();
    while(inFile.get() == 'v') {       // relevant
        inFile >> x;       // relevant
        inFile >> y;       // relevant
        inFile >> z;       // relevant
        inFile.get();       // relevant
        w = (wire_vertex)malloc(sizeof(wire_vertex));
        w[0] = x;
        w[1] = y;
        w[2] = z;
        *wire << w;

reads a file like:
v 360.0 10.2762631109763 83.3377366307129
v 360.0 4.60001345097578 100.05942891116
v 360.0 1.15494371453559 117.378964050293
v 360.0 0.0 135.0
v 360.0 0.0 270.0
v 360.0 0.769962476357065 281.747357299805

Sir, e^iπ + 1 = 0, hence God exists; reply!
Quote this message in a reply
Posts: 5,143
Joined: 2002.04
Post: #3
If you're using the terminal to run your progam, something like this:

/path/to/your/program < /path/to/your/data/file

or like this:

cat /path/to/your/data/file | /path/to/your/program
Quote this message in a reply
Posts: 321
Joined: 2004.10
Post: #4
Mr. unknown,

Yes, that's exactly how I've approached my file io before. Good to see that I'm not alone.

Mr. OneSadCookie,

As usual your answer is right on the money. Although I'll have to study a bit second idiom to fully grasp it.

Say, If I'm trying to run the program within Xcode, can I just open up a terminal window and type in the command? Or am I just out of luck? I'll contiunue to play around a bit in Xcode.
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Screen Anti-aliasing basic question WhatMeWorry 7 5,164 Mar 1, 2006 12:29 PM
Last Post: OneSadCookie