If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

I learned this from a tutorial and i mostly understood it but i'm having some problems to understand why it needs <while(asd.good()){> before cout and another <asd >> asdasd;> after cout. Without the while i only have the first word of the txt and without the second <asd >> asdasd> i have compile error. Any clarification d be really appreciated. Thanks

Re: noob tutorial (reading file) clarification

Code:

asd >> asdasd;

This reads characters from the file stream asd to the char array asdasd until a terminating char is read (space, tab, newline , end-of-file etc). It doesn't read the whole file. Hence you need to keep reading the next set of characters until all have been read. This is the purpose of the while loop. Effectively it's saying that while characters have been read (ie eveything is good) output the characters and get the next set of characters. If there are no more characters in the file to read (ie end of file reached) then everything is not good and the while loop terminates. You can actually rewrite this loop more simply as

Code:

while (asd >> asdasd){
cout << asdasd << " " << " ";
}

Which does the same job.

I don't know which tutorial you got it from but the program has a serious flaw. As I said above, characters are read into the asdasd array until a terminating char is read. This can be any size. However, asdasd has only been declared to hold a maximum of 50 chars (including the terminating NULL so effectively only 49). If the file has a sequence of non-terminating characters longer than 49 characters then the program will happily read them from the file and overwrite what ever happens to be in memory following the asdasd array. This is called buffer overrun and is a security issue. A better way of reading is to use the string class where the programmer doesn't have to be aware of the size of memory being used. The code could then be

Also you normally don't terminate a program by calling exit() unless the situation is disastrous. Normally return is used with the exit code. There is potentially a problem using exit() in this situation as when you call the exit() or _exit() functions, the destructors for any temporary or automatic objects that exist at the time of the call are not called. An automatic object is an object that is defined in a function where the object is not declared to be static. A temporary object is an object created by the compiler.