PDA

View Full Version : basic C++ <iostream> question


WhatMeWorry
2006.06.18, 08:48 PM
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
else
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.

unknown
2006.06.18, 08:53 PM
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

OneSadCookie
2006.06.18, 08:54 PM
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

WhatMeWorry
2006.06.18, 10:22 PM
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.