Welcome! Log In Create A New Profile

Advanced

I/O streams help...What's wrong with this code

Posted by Dumzaz 
Announcements Last Post
Announcement SoC Curricula 09/30/2017 01:08PM
Announcement Demarcation or scoping of examinations and assessment 02/13/2017 07:59AM
Announcement School of Computing Short Learning Programmes 11/24/2014 08:37AM
Announcement Unisa contact information 07/28/2011 01:28PM
I/O streams help...What's wrong with this code
May 25, 2008 02:47PM
What's wrong with this code

Please help here. I cannot figure out whats wrong with this code. I need this to read each number from the file numbers.dat, store it in variable next, and sum the numbers while there are numbers to read. It keeps giving me 0 as the output.

#include <fstream>
#include <iostream>

int main( )
{
using namespace std;
ifstream ins;
ins.open("numbers.dat"winking smiley;
int next;
int sum = 0;

ins >> next;
while (ins >> next)
{

sum = sum + next;
ins >> next;
}
ins.close();
cout << sum << endl;
return 0;
}

Numbers.dat

1
2
3
4
5

Am obviously missing something ... pls help !!!!!!!!!!!!
Re: I/O streams help...What's wrong with this code
May 25, 2008 03:54PM
Got it. Was working off two different folders. Should have used

if (ins.fail( ))
{
cout << "Input file opening failed.\n";
exit(1);
}

would have saved myself some time.
avatar spinning smiley sticking its tongue out Re: I/O streams help...What's wrong with this code
May 25, 2008 07:11PM
Hi, another problem is:


ins >> next; // PROBLEM

while (ins >> next)

You are throwing away the first value you are reading !!! with
ins >> next
, you only need the while

--------------------------------------------------------------
Don't Assume Everything is a Nail Just Because You Have a Really Big Hammer
avatar Re: I/O streams help...What's wrong with this code
May 26, 2008 05:46PM
There are two forms of the conditional loop: the while (condition) { } loop and the do { } while (condtiton);

The former runs zero to many times, the latter runs once till many times.

You have shown in your logic that you want to read something in at least once, indicating that you should use the latter form. I suggest changing your code accordingly.

Secondly, for readability's sake, please use the eof() function of the iostream class instead of the return value of the overloaded operator>>. eof stands for "end of file" and makes more readable sense to say "while not end of file" than while (ins >> next)

do 
  { 
  ins >> next;
  sum = sum + next; 
  } 
while (!ins.eof());

ins.close();

I wouldn't suggest this though since you must take into consideration that you might be opening an empty file. I would suggest using the first kind of conditional loop instead.
while (!ins.eof())
  { 
  ins >> next;
  sum = sum + next; 
  } 

ins.close();

Thirdly, please stop using exit, use return instead. Get some tippex, and erase it from every tut letter and page in your textbook. Forget it even exists.

if (ins.fail( )) 
  { 
  cout << "Input file opening failed.\n"; 
  return 1; 
  }
is the better alternative.
avatar hot smiley Re: I/O streams help...What's wrong with this code
May 26, 2008 09:29PM
@robanaurochs
>> Thirdly, please stop using exit, use return instead. Get some tippex, and erase it from every tut letter and page in your textbook. Forget it even exists.

Wow, easy here Silver. If your actualy paying attention to the way the course material is structured, you will see that exit and not return is used: ie page 327 - DISPLAY 6.6

You will also see the function make_neat makes use of:
while (messy_file >> next)

Please keep your answers relative to assignment question and not jump too ahead on the course material with your knowledge. I'm getting quiet a few private mails from people that feel uncomfortable asking their questions on Phorum because of "I-know-it-all's" with their remarks.

--------------------------------------------------------------
Don't Assume Everything is a Nail Just Because You Have a Really Big Hammer
Re: I/O streams help...What's wrong with this code
May 27, 2008 09:03AM
I must say though, (a0 is a much simpler implementation than (b). However the book says we need to use (b) when dealing with numbers and (a) when dealing with characters.

(a) while (!ins.eof())
{
ins >> next;
sum = sum + next;
}


(b) while (messy_file >> next)
sum = sum + next;
avatar Re: I/O streams help...What's wrong with this code
May 27, 2008 01:36PM
exit should never be used just like goto should never be used. They're relics of c programming. If your compiler isn't geared to override the standard way of aborting your program, you'll crash your system.

In short, if you can't justify using exit (and "it's in the textbook" is not a valid justification), you should use return instead.

You're lucky you've got the textbook you do, it's a lot better than the one that I used in first year and it wouldn't surprise me that all the complaints over the years were the reason they changed the textbook.

The fact that it's a different textbook doesn't mean it doesn't have mistakes or follow old programming paradigms.

Ask yourself what the point of return is and what the point of exit is.

The main function has a return type of int (normally) that you can use to return an exit code to the operating system. This number is chosen completely arbitrarily and only has meaning to the programmer and the people who actually try and read this number from the console. There is a convension that exists that says that if your program terminates properly without any errors, the return value is zero. Other return values can mean anything you want, an error could have a specific error number or you could just use the convesional 1 or -1 which just means (there was an error that cause the program to terminate).

You can do all of that with the return statement. There is no need for the archaic exit function.
Re: I/O streams help...What's wrong with this code
May 27, 2008 05:24PM
"it's like goto", "it's a relic of C", "it will crash the system" and "the new textbook is wrong too" are not valid justifications either.

goto is to be avoided in the context of structured languages because there are better alternatives and because it's a bad habit to use unstructured coding in a structured language.

goto is still appropriate (and necessary) in assembly programming.

exit() is not counter to the ideal of either structured languages or object oriented languages, but it should be avoided in C++ is because it doesn't properly call all object destructors.

Those are valid justifications.

Now, I am still waiting for you to justify using <math.h> instead of <cmath> in C++ programs.
avatar Re: I/O streams help...What's wrong with this code
May 27, 2008 10:20PM
Yes, I agree with you on the reason for not using exit(). I've mentioned it quite a bit in a previous thread so I left the justification there.

As far as the headers go, I have rechecked the code and placed a rebuttal in the thread that discusses it.
Re: I/O streams help...What's wrong with this code
May 28, 2008 09:44AM
when writing command line programs, I like using the following function because I like validating as many return codes as possible, and sometimes you just have to abend. I prefer it if I can control the abends.

void error(string message)
{
    cout<<"error: "<<message<<endl;
    system("pause"winking smiley;
    exit(-1);
}
Re: I/O streams help...What's wrong with this code
May 28, 2008 11:03AM
Randal,

I've seen that use before, but a more OOP way would be to use exceptions. That way you can escalate the error up to a point where you can exit gracefully. It's more work though.
Re: I/O streams help...What's wrong with this code
May 28, 2008 11:14AM
true
avatar Re: I/O streams help...What's wrong with this code
May 28, 2008 01:56PM
You can still evaluate the exit codes with the return statement. That's why you can make main() have a return type of int.

Using exit in another function will abort the program but like Gustav said, c++ has a more robust way of terminating the program that will still make sure that your classes are destroyed properly. Chapter 16 handles exceptions.

int main() 
  {
  // some code

  try
    {
    // some code that causes some kind of fault in the program
    if (errorCondition)
      {
      throw "errorCondition is true";
      }
    }
  catch (string errorMessage)
    {
    cout << "error: " << errorMessage << endl;
    return -1;
    }
  
  return 0; // end the program, telling the OS that there were no errors
  }

Then you can still use your console script files to check the error codes. In the MS console, you'd use the ERRORLEVEL variable to get the return code.
Re: I/O streams help...What's wrong with this code
May 28, 2008 03:11PM
Damn, You guys are far. i havent even opend the text book very far. those letters are too small
Re: I/O streams help...What's wrong with this code
May 30, 2008 12:34AM
Yeah, but we cheated. We're all programmers.
avatar Re: I/O streams help...What's wrong with this code
May 30, 2008 10:31AM
And some of us have forgotten how to write C/C++ code. On the other hand, there was a time I was thinking of joining a Linux project to write some device drivers. Then I woke up and realised I am just a normal programmer with an actual life besides PCs.
avatar Re: I/O streams help...What's wrong with this code
May 30, 2008 11:02AM
@Skazzy

Ok, so stop posting comments about how much of a wank certain things are and start studying. Come back to the phorums when you can at least do a "Hello world"... smile

--------------------------------------------------------------
Don't Assume Everything is a Nail Just Because You Have a Really Big Hammer
Re: I/O streams help...What's wrong with this code
May 30, 2008 11:23AM
Henry,

I thought "normal programmers" were the ones who had no actual lives besides PCs?

(Yes, I'm a hacker, and proud of it.)
avatar Re: I/O streams help...What's wrong with this code
May 30, 2008 11:09PM
Mmm. I was referring to guys who have to time and brains to devote their lives to nice projects that is actually intellectually challenging.

I might be there one day when my kids are busy with their own lives, although my current project is not too bad.

I am doing a business application using Spring/Hibernate/Oracle. I just received my new Hibernate book from Amazon, the Spring one is on the way, and well, I have more PDFs on Oracle on my PC than I have life left to read. For the past 3 years I did client development (vertical market) using C#/.NET, so my DB knowledge is sadly lacking.
Sorry, only registered users may post in this forum.

Click here to login