473,378 Members | 1,346 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

fstream & parameters...

Hi,

I was just wondering if someone would like to comment on these two issues.
I had a 15 minute wander around some sites and was curious about loading
files (plain ASCII I think will do for a beginner right now). So I looked
into the fstream library file.
I saved 5 lines to the file:

testing, testing
this is
a
test... 1
2, 3...

And used a while loop (using is.good() ) to load the file using the
getline(is, string) function, like so:

#include <iostream>
#include <stdlib.h>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
ifstream is;
is.open("test.txt");
string sline;
while(is.good()){
getline(is, sline);
cout << sline << endl;
}
return 0;
}

Now is there any errors in this at all (apart from the obvious lack of
is.close())? I'm refering mainly to the method, remembering the VB6
lineinput(#) and the way it wasn't exactly a line, especially on binary
files...
Please comment on any bad form I've used above, as I have only started...
Are there better way's at loading files? Anything would be helpful.

Another thing I looked into was the passed argv*[] parameter, which I
(correctly) guessed to be the passed parameter's at run-time (is that term
correct?)... This I would really like someone to clarify for me.
I experimented, and knew that assigning a char pointer to a string like so:
char *test = "testing...";
string stest = test;
would work... I'm guessing the char *test is a pointer to a character array
(effectively?) and so the assignment of "testing..." get's put into that
char array.
The string see's this pointer to that array and so loads that.

So then I experimented with the *argv[], and noticed that:
string stest = *argv; prodeuced the first parameter passed - but that was
all. Next was:
string stest = argv; which didn't compile (I go by experimentation) so next
was:
string stest = *argv[1]; which produced the first letter of the first
parameter... And so:
string stest = argv[1]; is the first parameter again, and [2] is the second
(and [n] is the nth)...
Now let me try to understand this one.
string stest = *argv is a pointer to the start of the array... so it
defaults the the 'first' array and so get's the first parameter.
string stest = argv[1] is also a pointer - but this time referencing to the
first array of strings - but it's a reference to the whole array instead of
the starting place?
string stest = *argv[1] is a pointer to the starting place of the array -
therefore the first character.... Just as if I put *test in the other string
example above.

So therefore argv is a pointer to a list of pointers to char arrays? Is that
right?
I do find pointers a tad bit confusing as I'm just getting into them, so I'm
trying to understand them as best as I can early on.

Any feed back will be extremely helpful.
I thank you for reading this post.

--
=========
Comp Whizz
=========
(From The Server-Side)
Jul 22 '05 #1
7 2850
Computer Whizz wrote:
And used a while loop (using is.good() ) to load the file using the
getline(is, string) function, like so: while(is.good()){
getline(is, sline);
cout << sline << endl;
}
This would apparently read the last line twice although it actually
does
not: you should always test the stream *after* you have tried to read
something. Prior to the attempt to read something, the stream cannot
know what you will attempt next and thus cannot tell reliably whether
it will succeed. It can only tell that it will fail in some situations,
e.g. if a prior attempt to read something failed. You should write the
above loops as:

| for (std::string sline; std::getline(is, sline; )
| std::cout << sline << "\n";
Another thing I looked into was the passed argv*[] parameter, which I (correctly) guessed to be the passed parameter's at run-time (is that term correct?)... This I would really like someone to clarify for me.


You should *read* a tutorial rather than experimenting! Experimenting
might give you a working knowledge of Basic, it won't give you what you
need to know to use C++! C++ is a powerful tool which you better know
how to use correctly to avoid serious damage. It is much like operating
with a chainsaw.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting

Jul 22 '05 #2
On Mon, 6 Dec 2004 08:45:04 -0000, "Computer Whizz"
<ol*********@hotmail.com> wrote:
Hi,

I was just wondering if someone would like to comment on these two issues.
I had a 15 minute wander around some sites and was curious about loading
files (plain ASCII I think will do for a beginner right now). So I looked
into the fstream library file.
I saved 5 lines to the file:

testing, testing
this is
a
test... 1
2, 3...

And used a while loop (using is.good() ) to load the file using the
getline(is, string) function, like so:

#include <iostream>
#include <stdlib.h>
#include <fstream>

using namespace std;

int main(int argc, char *argv[])
{
ifstream is;
is.open("test.txt");
string sline;
while(is.good()){
getline(is, sline);
cout << sline << endl;
}
That's wrong, since it doesn't check whether the getline call worked.
Instead, you should do:

while(getline(is, sline))
{
cout << sline << '\n';
}

if (!is.eof)
{
//something bad happened.
}
return 0;
}

Now is there any errors in this at all (apart from the obvious lack of
is.close())?
The stream is closed (and flushed) automatically on destruction.

I'm refering mainly to the method, remembering the VB6lineinput(#) and the way it wasn't exactly a line, especially on binary
files...
Please comment on any bad form I've used above, as I have only started...
Are there better way's at loading files? Anything would be helpful.
That depends on what you are doing with the file. If you want to
process it a line at a time, then the above is the best way to do it.
If you just want to load the file into a string, there are other ways.
Another thing I looked into was the passed argv*[] parameter, which I
(correctly) guessed to be the passed parameter's at run-time (is that term
correct?)... This I would really like someone to clarify for me.
I experimented, and knew that assigning a char pointer to a string like so:
char *test = "testing...";
string stest = test;
would work... I'm guessing the char *test is a pointer to a character array
(effectively?) and so the assignment of "testing..." get's put into that
char array.
"test" above is just a pointer, so you are simply assigning that
pointer to point to the start of the string literal "testing...".
String literals are held in the program's code, and are valid for the
duration of a program. However, since modifying string literals gives
undefined behaviour, you should instead do:

char const* test = "testing...";
The string see's this pointer to that array and so loads that.
std::string has a constructor that takes a pointer to a null
terminated char array, and this constructor basically follows that
pointer and loads the std::string with the characters pointed to, up
to the first '\0' character.
So then I experimented with the *argv[], and noticed that:
string stest = *argv; prodeuced the first parameter passed - but that was
all. Next was:
string stest = argv; which didn't compile (I go by experimentation) so next
was:
string stest = *argv[1]; which produced the first letter of the first
parameter... And so:
string stest = argv[1]; is the first parameter again, and [2] is the second
(and [n] is the nth)...
Now let me try to understand this one.
string stest = *argv is a pointer to the start of the array... so it
defaults the the 'first' array and so get's the first parameter.
*argv is just a dereference of argv. argv is a pointer to a pointer to
char. Dereferencing it gives a pointer to char, and argv is set up so
that this points to a null-terminated string. You could also have
written:

string stest = argv[0];

(remember, a[n] == *(a + n))
string stest = argv[1] is also a pointer - but this time referencing to the
first array of strings - but it's a reference to the whole array instead of
the starting place?
argv[1] references the *second* array - remember that we index from 0.

Argv is set up like this (with a -> representing what a pointer is
pointing to). The array is contiguous - the pointer element1 lies
directly after element0 in memory.
argv (type=char**)->
element0 (type=char*)->"Name of the program"
element1 (type=char*)->"First command line arg"
element2 (type=char*)->"Second command line arg"
...

The number of elements is argc.
string stest = *argv[1] is a pointer to the starting place of the array -
therefore the first character.... Just as if I put *test in the other string
example above.
Right. You could also write argv[1][0].

So therefore argv is a pointer to a list of pointers to char arrays? Is that
right?
Right.
I do find pointers a tad bit confusing as I'm just getting into them, so I'm
trying to understand them as best as I can early on.


I think everyone finds them confusing. There are two things to
consider: what your pointer is pointing at (which may be a single
object or an array of objects), and the type of the thing it is
pointing at.

Tom
Jul 22 '05 #3

"Tom Widmer" <to********@hotmail.com> wrote in message
news:9f********************************@4ax.com...
On Mon, 6 Dec 2004 08:45:04 -0000, "Computer Whizz"
<ol*********@hotmail.com> wrote:
That's wrong, since it doesn't check whether the getline call worked.
Instead, you should do:

while(getline(is, sline))
{
cout << sline << '\n';
}

if (!is.eof)
{
//something bad happened.
}
Thanks very much Tom. I was just taking an example off of a site and
basically experimented a tad. When I find something interesting I like to
find out a little bit to satisfy me until I look into it fully... That while
above did pop into my mind though.
Now is there any errors in this at all (apart from the obvious lack of
is.close())?


The stream is closed (and flushed) automatically on destruction.


Ah good. I didn't want to leave the file open like you can do so many times
in VB...
Is there a "channel" that get's set automatically by any chance? I may call
it a channel because I got that from the sinclairQL stuff, but in VB you
would need to find a "freefile" channel and use it. Was wondering if there
are similarities.

That depends on what you are doing with the file. If you want to
process it a line at a time, then the above is the best way to do it.
If you just want to load the file into a string, there are other ways.
I did also look into "string << is;" but that is word-by-word, ignoring all
spaces and newlines - correct?
If I wanted to load them into a vector<string>, for line-by-line purposes,
would the getline() be fine or is there a better way?

I think for binary files etc I'll wait until I read about them.
char *test = "testing...";
string stest = test;
would work... I'm guessing the char *test is a pointer to a character
array
(effectively?) and so the assignment of "testing..." get's put into that
char array.
"test" above is just a pointer, so you are simply assigning that
pointer to point to the start of the string literal "testing...".
String literals are held in the program's code, and are valid for the
duration of a program. However, since modifying string literals gives
undefined behaviour, you should instead do:

char const* test = "testing...";


I wasn't planning on madifying it at all really, and usually I use
std::strings as they are much nicer to work with.
The string see's this pointer to that array and so loads that.
std::string has a constructor that takes a pointer to a null
terminated char array, and this constructor basically follows that
pointer and loads the std::string with the characters pointed to, up
to the first '\0' character.


Thanks. That explains it very well.
So then I experimented with the *argv[], and noticed that:
string stest = *argv; prodeuced the first parameter passed - but that was
all. Next was:
string stest = argv; which didn't compile (I go by experimentation) so
next
was:
string stest = *argv[1]; which produced the first letter of the first
parameter... And so:
string stest = argv[1]; is the first parameter again, and [2] is the
second
(and [n] is the nth)...
Now let me try to understand this one.
string stest = *argv is a pointer to the start of the array... so it
defaults the the 'first' array and so get's the first parameter.
*argv is just a dereference of argv. argv is a pointer to a pointer to
char. Dereferencing it gives a pointer to char, and argv is set up so
that this points to a null-terminated string. You could also have
written:


Ahh, okay. Cheers for the info.

string stest = argv[0];

(remember, a[n] == *(a + n))
string stest = argv[1] is also a pointer - but this time referencing to
the
first array of strings - but it's a reference to the whole array instead
of
the starting place?
argv[1] references the *second* array - remember that we index from 0.


Yes, sorry. I did actually write 0 in code, but was in the middle of
something else which used 1 as the base - long story, basically the 'var[0]'
is turned into 'var'... It's not a "proper" programming language etc, and I
switched over and wrote [1] - my mistake.

Argv is set up like this (with a -> representing what a pointer is
pointing to). The array is contiguous - the pointer element1 lies
directly after element0 in memory.
argv (type=char**)->
element0 (type=char*)->"Name of the program"
element1 (type=char*)->"First command line arg"
element2 (type=char*)->"Second command line arg"
...

The number of elements is argc.
Thank you.That does help make an image in my mind.
string stest = *argv[1] is a pointer to the starting place of the array -
therefore the first character.... Just as if I put *test in the other
string
example above.
Right. You could also write argv[1][0].


Ooo... I guess it is logical - but I wouldn't have guessed that. Thanks
again.

So therefore argv is a pointer to a list of pointers to char arrays? Is
that
right?
Right.


Great.
I do find pointers a tad bit confusing as I'm just getting into them, so
I'm
trying to understand them as best as I can early on.


I think everyone finds them confusing. There are two things to
consider: what your pointer is pointing at (which may be a single
object or an array of objects), and the type of the thing it is
pointing at.

Tom


And with your help I feel like I've started to get the correct grip on them.
Thank you.

--
=========
Comp Whizz
=========
(From The Server-Side)
Jul 22 '05 #4

Computer Whizz wrote:
"Tom Widmer" <to********@hotmail.com> wrote in message
news:9f********************************@4ax.com...
On Mon, 6 Dec 2004 08:45:04 -0000, "Computer Whizz"
<ol*********@hotmail.com> wrote:
Ah good. I didn't want to leave the file open like you can do so many times in VB...
Is there a "channel" that get's set automatically by any chance? I may call it a channel because I got that from the sinclairQL stuff, but in VB you would need to find a "freefile" channel and use it. Was wondering if there are similarities.
Not really. The 'fstream' object you use /is/ what you'd call the
channel.
However, in C++ objects have constructors (aka ctor) and destructors
(dtor)
which work automatically. If you give the fstream ctor a filename, it
will
"open" that file for you. When you stop using it, the dtor will "close"
it.
You can also call the .close( ) member earlier.
I did also look into "string << is;" but that is word-by-word, ignoring all spaces and newlines - correct? Yes.
If I wanted to load them into a vector<string>, for line-by-line purposes, would the getline() be fine or is there a better way?

There are other ways, but this one is very clear. Usually, that is what
we call 'better' but for some programs "fast" is better than "easily
understood". Compare prices for faster CPUs and better developers, and
you'll see why.
BTW. try to figure out what this line does
std::vector<std::string> args ( argv, argv+argc );
Regards,
Michiel Salters

Jul 22 '05 #5

"Dietmar Kuehl" <di***********@yahoo.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
Computer Whizz wrote:
And used a while loop (using is.good() ) to load the file using the
getline(is, string) function, like so:
while(is.good()){
getline(is, sline);
cout << sline << endl;
}


This would apparently read the last line twice although it actually
does not: you should always test the stream *after* you have tried to read
something. Prior to the attempt to read something, the stream cannot
know what you will attempt next and thus cannot tell reliably whether
it will succeed. It can only tell that it will fail in some situations,
e.g. if a prior attempt to read something failed. You should write the
above loops as:

| for (std::string sline; std::getline(is, sline; )
| std::cout << sline << "\n";


Ah, thank you. Although I do prefer the while(getline(is, sline)) {} in
another post.
Another thing I looked into was the passed argv*[] parameter, which I

(correctly) guessed to be the passed parameter's at run-time (is that

term
correct?)... This I would really like someone to clarify for me.


You should *read* a tutorial rather than experimenting! Experimenting
might give you a working knowledge of Basic, it won't give you what you
need to know to use C++! C++ is a powerful tool which you better know
how to use correctly to avoid serious damage. It is much like operating
with a chainsaw.
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.contendix.com> - Software Development & Consulting


I am currently reading through Advanced C++, and will probably go onto a STL
book (reference or not).
I much prefer examples and a reference on how to use the function, rather
than learning all technical words, which this book seems set on doing...
Don't get me wrong, it get's the point between two people much better, and I
will enevitably learn it - but more through experimentation and adaption.
I do however look up everything as much as I can online though, getting some
background on how to use the function/type correctly. That's why I am doing
things slowly.

I have no intention to compile a program without fully understanding it -
much like I have no intention to wield an active chainsaw without having
prior experience on lighter and inactive models.

--
=========
Comp Whizz
=========
(From The Server-Side)
Jul 22 '05 #6

"msalters" <Mi*************@logicacmg.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...

There are other ways, but this one is very clear. Usually, that is what
we call 'better' but for some programs "fast" is better than "easily
understood". Compare prices for faster CPUs and better developers, and
you'll see why.
Yep - I will definately get into the speed thing later on - but
understanding it right now is the most important thing.


BTW. try to figure out what this line does
std::vector<std::string> args ( argv, argv+argc );
Regards,
Michiel Salters


The declaration defines a vector (array in my mind) of strings - 2
dimensional. One with argv and another with argv concatinated with argc?
I'll try it out after work - It'll be interesting to see if I'm right.
Thanks...

--
=========
Comp Whizz
=========
(From The Server-Side)
Jul 22 '05 #7

"Computer Whizz" <ol*********@hotmail.com> wrote in message
news:cp**********@newsg1.svr.pol.co.uk...
BTW. try to figure out what this line does
std::vector<std::string> args ( argv, argv+argc );
Regards,
Michiel Salters


Just to follow up - I tried it, and after much fiddling I tried to output
the data.... In my round-about ways it led me to research vector's a little
bit and so I found an ( beginning pointer, end pointer ) bit...

So it creates an array of strings, from the starting pointer (argv) to the
ending pointer (argv + argc)...

Thank you very much for the info there...

--
=========
Comp Whizz
=========
(The C++ beginner)
Jul 22 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Armando | last post by:
Hallo ! I habe some error in my programm,because i use <fstream.h>,I want to use <fstream> but i donīt know which fonctions i must modify in my program ? Thanks you for your help. Armando.
3
by: Manuel Maria Diaz Gomez | last post by:
Hi everybody, This is probably trivial, but I just can't see it. In the followinf function: /*-------------------------------------------------*/ File::loadFile(string inputFile)...
16
by: Steven T. Hatton | last post by:
In the following code, the only way I can figure out to pass an array of const is by setting the template argument to const in the instanciation expression. It would be (or seem to me) better if I...
3
by: kieran | last post by:
Hi, I'm using fstream.get to read in a character from a file, then print it on the screen. I have a file called test.log that contains "Hello, World!", but when I try and print the contents out on...
3
by: John Smith | last post by:
I would like to write over a file if it exists (or create one if it doesn't exist). The following codes do nothing if the file already exists. How do I get it to overwrite an existing file? ...
3
by: John R. Delaney | last post by:
If I try to declare an object of type fstream (or ofstream), I run into a compilation error refering to an __something function or variable. Please note, I am including <fstream>, not <fstream.h>....
6
by: Rich | last post by:
Hello, I have to create a table in an Access mdb (remotely) on the fly. Create Table tbl1(fld1 Integer, fld2 varchar(10), fld3...) Then I have to insert data: Insert Into tbl1 Values(" &...
9
by: Someonekicked | last post by:
In my program, I need to open multiple files, and I wont know till after the program execution how many of them (user will enter that value). So I am using a vector of fstream. I am using fstream...
1
by: MForey | last post by:
I'm attempting to create a program that uses fstream objects to read/write to files. However, it is currently balky at best. The fstream.write call doesn't return an error, but the modified data...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.