Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Programming Help needed (simple)

Options
  • 16-11-2003 3:58pm
    #1
    Closed Accounts Posts: 439 ✭✭


    I have to write a program that will:

    1) Recieve input (numbers) from an input text file
    2) Re-display input on screen.
    3) show the number of inputs (numbers).
    4) Stop inputing numbers when it reachs number -1.
    5) Get the average of all numbers.
    6) Redirect out to an output file.

    Location of the input and out put files must be entered at the comand line. I can do it in unix like this ./program.cpp <inputfile.txt >output.txt but that won't work for vc++ (i think)

    I've 2, 3 and 4 pretty much nailed, but i haven't a clue where to go with the rest, and my book seems to be absent of any information on inputing multiply items at once.

    This is what i've done so far, and it has taken me hours.


    [PHP] #include <iostream>
    using namespace std;

    int main()

    {
    int counter = 0;
    double number =0;

    cout<<"Please enter a list of numbers.\n";
    cout<<"and then press enter.\n";

    do
    {

    cin >> number;
    cout <<number<<"\n";

    counter++;
    }

    while (number > -1);



    cout<<"There was "<<counter<<" numbers\n";

    cout<<"goodbye.\n";

    return 0;
    }




    [/PHP]


«1

Comments

  • Registered Users Posts: 1,372 ✭✭✭silverside


    Read up on ifstream / ofstream , they will let you treat files the same way you are now using cin and cout.

    To specify the filenames on the command line use argc and argv.

    This should all be covered in your book. If not go to the library and get a new one, or use google.


  • Registered Users Posts: 2,281 ✭✭✭DeadBankClerk


    [PHP] #include <iostream>
    using namespace std;

    int main()
    {
    int total_numbers = 0;
    float number = 0.0f;
    float sum = 0.0f

    cout << "Please enter a list of numbers." << endl << "and then press enter." << endl;

    while ( true )
    {
    cin >> number;
    if (number == -1.0f) break;
    cout << number << endl;
    total_numbers++;
    sum += number;
    }
    cout<<"There was " << total_numbers<<" numbers\n";
    if (total_numbers)
    cout << "Average: " << sum/total_numbers << endl;
    else
    cout << "Average: 0" << endl;
    return EXIT_SUCCESS;
    }
    [/PHP]


  • Registered Users Posts: 1,562 ✭✭✭Snaga


    as for number 5, whats so difficult here?

    You need to add each number that was entered and divide by the final number count.

    (hint - use another variable to hold the ongoing total of inputted numbers, as you are over-writing the number variable on each iteration of your loop.)

    <edit>
    dbc - no point doing his homework for him
    </edit>


  • Closed Accounts Posts: 3,322 ✭✭✭Repli


       ifstrem in("input.txt");
       ofstream out("out.txt");
       in >> data1 >> data2 >> data3;
       in.close();
       // data manipulation here
       out << data1 << data2 << data3 << endl;
       out.close();
    


  • Closed Accounts Posts: 439 ✭✭Atreides


    I should have added I've been programming for about two weeks.

    Snaga: I figured I would have to do that, but everytime I tried to code to do that, I got into a really big muddle which spiraled into really large complexity. Only Have seeing DBC's example did I realize my mistake in not using the += thing, to little sleep I think. As for homework, I can either do this or not do this, the only person who cares if I understand this is me.

    DeadBankClerk: Thank you for that, I can just about follow it.
    few questions.
    while ( true ) and then if (number == -1.0f) break
    this doesn't count the sentential (which is what i wanted), but if I say while (number > -1.0f) it does(not what i wanted), why? what exactly does the if break statement do, its not covered in my material.

    see where you say
    if (total_numbers)

    does that mean, If total_numbers is a positive real number do the following. Just asking because I would have if total_numbers !=0, is it the same thing, or does it make a difference?

    Repli: Completely over my head, but I'm learning.


  • Advertisement
  • Registered Users Posts: 2,758 ✭✭✭Peace


    Ya know huys if you took a minute to comment your code it would help this guy out a lot....

    I can read it fine, but for people , like skanger, who hasn't been programming for long it would make a huge difference.

    Just sayin,.....


  • Closed Accounts Posts: 3,322 ✭✭✭Repli


    Well its just to handle the I/O part of your program..

    I think DBC assumed you meant if the users presses -1 then the program exits. But from the looks of it what you want to do is keep inputting numbers until the users enters a number less than 0. The break statement will exit the while loop - simple as that.
    if(total_numbers) tests if total_numbers is >0 it evaluates to true if it is


  • Closed Accounts Posts: 439 ✭✭Atreides


    Here what i've some up with, but after i enter the input and output file name it just sits there.

    Edit: ixed that problem.

    I've a new one
    [PHP] if (total_numbers)
    cout << "Average: " << average << endl;
    out_stream<< "Average: " << average << endl;

    else
    cout << "Average: 0" << endl;
    out_stream<< "Average: " << average << endl;
    [/PHP]

    I get illegal else without matching if. But as far as i can see it does match?


  • Registered Users Posts: 1,372 ✭✭✭silverside


    You're doing fine so far. What you should do now is run the program in the debugger to see exactly what is happening. - Are the numbers being read correctly? Is a -1 being read from the file? Is it breaking out of the loop? The debugger will tell you all this - play around with it.

    Also be aware that comparing floating point numbers using == can be error prone. If you have for example

    float a=2.0 / 4.0;
    float b=0.5;

    then a==b may or may not be true. To get around this, test using < or >, or convert to integers.


  • Closed Accounts Posts: 439 ✭✭Atreides


    For some reason the problem went away when i added

    [PHP] if (out_stream.fail())
    {
    cout<<"Output file opening failed.\n";
    exit(1);
    }
    [/PHP]

    For in_stream and out_stream after calling on them to open


  • Advertisement
  • Registered Users Posts: 1,372 ✭✭✭silverside


    You need to put braces around the code in the if and else

    i.e.
    if (condition)
    {
    do something part 1;
    do something part 2;
    }
    else
    {
    do something else;
    do more something else;
    }

    You got away with leaving the brackets out when you only had one command after the if, but its always a good idea to put the brackets in anyway as it makes your code clearer. Althogh others would disagree.


  • Registered Users Posts: 1,372 ✭✭✭silverside


    Welcome to the world of the programmer
    :-)
    Lots of your time will be spent fixing these little problems so it makes life easier if you put in lots of comments and error checking, layout your code in a good style (coding standards) and always single-step through new code if you can to see exactly whats happening.

    Read 'Code Complete' if you can - its interesting and useful.


  • Closed Accounts Posts: 439 ✭✭Atreides


    Thank you for that, its actually overlooked in the book. Finally completed this thing and I feel a real sense of achievement. Even added the option to reuse the program. I feel I went overboard somewhat, since streams and stuff like that are in chapter five and I was doing an exercise from chapter two (or meant to be).

    Heres the finished product for anyone interested.

    [PHP] #include <iostream>
    #include <fstream>
    using namespace std;

    int main()
    {
    int total_numbers = 0;
    char in_file_name[21], out_file_name[21], ans;
    float number = 0.0f;
    float sum = 0.0f, average = 0.0f;
    ifstream in_stream;
    ofstream out_stream;

    do
    {

    cout<< "I will sum the list of numbers taken from the input file,\n"
    << "obtain an average value, and out put the results to the output file\n";
    cout<<"Enter the input file name:\n";
    cin>> in_file_name;
    cout<<"Enter the output file name:\n";
    cin>> out_file_name;

    in_stream.open(in_file_name);

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

    }

    out_stream.open(out_file_name);

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


    while (true)
    {
    in_stream>> number;
    if (number == -1.0f) break;
    out_stream<< number << endl;
    total_numbers++;
    sum += number;
    }

    average = sum/total_numbers;
    out_stream<<"There was " << total_numbers<<" numbers\n";
    cout<<"There was " << total_numbers<<" numbers\n";


    if (total_numbers)
    {out_stream<< "Average: " << average << endl;
    cout << "Average: " << average << endl;}
    else
    {out_stream<< "Average: " << average << endl;
    cout << "Average: 0" << endl;}



    in_stream.close();
    out_stream.close();

    cout<< "Do you want to use the program again.\n"
    << "Press y for Yes, n for no, and then press return.\n";
    cin>>ans;

    } while (ans =='y' || ans =='Y');

    cout<<"GoodBye.\n";

    return 0;
    } [/PHP]

    Question: am I an uber haxor yet? ;)


  • Closed Accounts Posts: 439 ✭✭Atreides


    Just thought of something, will the above be portable onto a mac?


  • Registered Users Posts: 2,281 ✭✭✭DeadBankClerk


    That code will port to mac perfectly (as far as i know), because you are using only the c++ standard library (such as iostream) which is pratform independant. You will find that think will not compile on a mac when you start doing windows only things, such as having a graphical user interface (windows and mouse).

    The break statement will exit the current loop immediatly. If you look at the loop, the first part of the loop exectutes every time. (ie, a number is read in from the file).

    If the number read in is not -1, then the rest of the loop will exectute (statements after the break).

    if ( number) is a short way of writing if (number != 0). I find that it makes your code much more readable if you are doing things with booleans eg:

    if (file_is_open)


  • Closed Accounts Posts: 439 ✭✭Atreides


    This has been quiet helpfull, afaik I'm to only one to have created the program. Probably have more questions next week.


  • Registered Users Posts: 2,281 ✭✭✭DeadBankClerk


    You have been the perfect poster.
    You have had a question, you have put up what code you have written so far, you have been polite and thanked people for their help.

    Gold star for you Skanger!


  • Closed Accounts Posts: 439 ✭✭Atreides


    This weeks assignment involves reading in a list of years, and saying weather or not they are leap years.

    What I want to say is if the number divided by four is an integer, print out "This is a leap year" after the number. But I can't quiet get the syntax straight. I've tried this

    [PHP] int main()
    {
    int number = 0, n = 1;
    char in_file_name[36],out_file_name[36], ans;
    ifstream in_stream;
    ofstream out_stream;

    do
    {
    cout<<"This program is designed to read in a sequence of years,\n";
    cout<<"and print out each year on a spearate line,\n";
    cout<<"followed by weather or not it is a leap year\n\n";

    cout<<"Enter the input file name:\n";
    cin>> in_file_name;
    cout<<"Enter the output file name:\n";
    cin>> out_file_name;

    in_stream.open(in_file_name);

    if(in_stream.fail())
    {
    cout<<"connot open the input file.\n";
    exit(1);
    }

    out_stream.open(out_file_name);

    if(in_stream.fail())
    {
    cout<<"connot open the output file.\n";
    exit(1);
    }

    while (true)
    {
    in_stream>> number;
    if (number == -1.0f) break;

    if ((number/4 == n*4)
    out_stream<< number << " The number is a leap year"<<endl;
    else
    out_stream<<number<<endl;

    }



    cout<< "Do you want to use the program again.\n"
    << "Press y for Yes, n for no, and then press return.\n";
    cin>>ans;

    }while ((ans =='y') || (ans =='Y'));

    cout<<"GoodBye.\n";

    return 0;
    }
    [/PHP]

    This doesn't work. Having thought about it, if I was able to set a range of integer values for n such as [0, infinite) that would probably solve it. Tired this (n > 0 && n < 99993) ; There are other conditions as well but I'm very confident if I get this one nailed I'll get the rest.


  • Registered Users Posts: 394 ✭✭colster


    YOu've got an extra opening '(' in the if checking if the year is a leap year.

    Also, the logic determing whether a year is a lea is faulty. If you want to check if a number is equally divisible by 4 then you should mod the number with 4 and check that it's equal to 0.
    E.g.

    if((year % 4) == 0)
    ....

    This basically says that if the remainder left after dividing a number by 4 is 0 blah blah.

    Another thing a leap year is not purely any year divisible by 4.
    I think there are a couple of other factors to consider when determining whether a year is a leap year.
    I think that if the year is the start of a century it isn't a leap year but if it's the start of a millenium it is.
    This mightn't be the exact rule but I know that it's a bit more complex than the year just being divisible by 4.

    Hope this helps


  • Registered Users Posts: 2,281 ✭✭✭DeadBankClerk


    You need the % (modulus) operator.
    a % b will give you the remainder of 'a divided by b'.

    if ( (year % 4) == 0) it's a leap year.


  • Advertisement
  • Closed Accounts Posts: 439 ✭✭Atreides


    Thank you, i came up with a really weird way of doing it. Divide the nubmer by four, then call that another number, (leap) then multiply leap by 4 and it should equal the orginal number, if four divded evenly into the orgianl number, other wise due to dividing an int by and int (which normalling results in a figure with a decimal point, which is ignored by c++)

    [PHP]while (true)

    {

    in_stream>> number;
    (number/4=leap);

    if (number == -1.0f) break;
    if (number == 4*leap)
    out_stream<< number << " The number is a leap year"<<endl;
    else
    out_stream<<number<<endl;

    }
    [/PHP]

    i get an error C2106: '=' : left operand must be l-value.

    edit: Btw i know the other conditions for a leap year, years that are dividable by 100 but not 400 are not leap years.


  • Closed Accounts Posts: 439 ✭✭Atreides


    Finally got it working correctly, Pretty pleased with myself. If there was a better way to get compound conditions then what I did down the bottom please tell me. I've a few un related questions.

    1)See the way I declared my opening statement, I know there's a way to do that with just the one cout, but I can't get it to work.How do I do this?

    2)Say I have several variables and I want to initializes them all to equal zero, how do I group initialize a larger number of variables

    [PHP] #include <iostream>
    #include <fstream>
    using namespace std;

    int main()
    {
    int number = 0, n = 1;
    char in_file_name[36],out_file_name[36], ans;
    ifstream fin;
    ofstream fout;
    (n > 0 && n < 99993);
    do
    {
    cout<<"This program is designed to read in a sequence of years,\n";
    cout<<"and print out each year on a spearate line,\n";
    cout<<"followed by weather or not it is a leap year\n\n";

    cout<<"Enter the input file name:\n";
    cin>> in_file_name;
    cout<<"Enter the output file name:\n";
    cin>> out_file_name;


    fin.open(in_file_name);

    if(fin.fail())
    {
    cout<<"connot open the input file.\n";
    exit(1);
    }

    fout.open(out_file_name);

    if(fout.fail())
    {
    cout<<"connot open the output file.\n";
    exit(1);
    }

    while (true)
    {
    fin>> number;
    if (number == -1.0f) break;
    if (((number%100) == 0)&&((number%400) == 0))

    {fout<<number<<" This is a leap year.\n";
    cout<<number<<" This is a leap year.\n";}

    else

    if (((number%4)==0) && ((number%100) != 0) )
    {fout<<number<<" This is a leap year.\n";
    cout<<number<<" This is a leap year.\n";}

    else {fout<<number<<endl;
    cout<<number<<endl;}

    }




    cout<< "Do you want to use the program again.\n"
    << "Press y for Yes, n for no, and then press return.\n";
    cin>>ans;

    }while ((ans =='y') || (ans =='Y'));

    cout<<"GoodBye.\n";

    return 0;
    } [/PHP]


  • Registered Users Posts: 491 ✭✭Silent Bob


    Originally posted by Skanger
    For some reason the problem went away when i added

    [PHP] if (out_stream.fail())
    {
    cout<<"Output file opening failed.\n";
    exit(1);
    }
    [/PHP]

    For in_stream and out_stream after calling on them to open
    You can only have one statement following an "if" statement.

    [php]
    if (condition)
    statement1
    else
    statement2
    [/php]

    However by placing curly braces ("{" and "}") around a set of statements, you turn them into a 'statement block' and the compiler treats the block as the statement that follows the "if".

    The short hand of writing "if (number != 0)" works because C++ treats any non-zero integer as a truth value of true and a zero integer as a truth value of false


  • Closed Accounts Posts: 439 ✭✭Atreides


    No i ment that the problem went away when i added that statement, not the brackets. Though thanks for your input.


  • Registered Users Posts: 491 ✭✭Silent Bob


    Sorry, I thought you were talking about your "illegal else without matching if" problem :)


  • Closed Accounts Posts: 9,314 ✭✭✭Talliesin


    Originally posted by colster
    Another thing a leap year is not purely any year divisible by 4.
    I think there are a couple of other factors to consider when determining whether a year is a leap year.
    I think that if the year is the start of a century it isn't a leap year but if it's the start of a millenium it is.
    This mightn't be the exact rule but I know that it's a bit more complex than the year just being divisible by 4.

    The exact rule is:
    1. A year is a leap year if it is divisible by 4, unless…
    2. It is divisible by 100, in which case it is a common year, unless…
    3. It is divisible by 400, in which case it is a leap year.

    Or in C++:
    bool isLeap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) 
    

    Rules for years prior to 1582C.E. (before the Gregorian Calendar) and after 40,000C.E. (which arguably shouldn't be a leap year although the abover rules say it is) vary according to different conventions. If you don't have a spec to follow on this use the Proleptic Gregorian - i.e. treat years before 1582 as if the Gregorian calendar had been around forever, have a year zero between 1B.C.E. and 1C.E. and don't have any further rules for working out leap years except for considering multiples of 4, 100 and 400.


  • Closed Accounts Posts: 439 ✭✭Atreides


    Question: I wrote this while statement it works grand, but I'm woundering why i couldn't do certain things

    [PHP] while (true)
    {
    if (time > 3.0f ) break; // Why wont this work with == 3.1?
    velocity = g*time;
    distance = (g/2)*(time*time); //why wont time^2 work?
    fout<<time<<"\t"<<velocity<<"\t"<<distance<< endl;
    cout<<time<<"\t"<<velocity<<"\t"<<distance<< endl;
    time += .1;
    }[/PHP]


  • Registered Users Posts: 2,281 ✭✭✭DeadBankClerk


    is time a float?


  • Closed Accounts Posts: 439 ✭✭Atreides


    yep. Strange thing is it worked if I put in 31, but not if I but in 3.1. The loop just continued forever.


  • Advertisement
  • Registered Users Posts: 491 ✭✭Silent Bob


    Originally posted by Skanger
    yep. Strange thing is it worked if I put in 31, but not if I but in 3.1. The loop just continued forever.
    If you are wondering why
    if (time == 3.1f)
    
    doesn't work it is probably because of how floats are stored in a register.

    You increment the value by 0.1 every iteration through the loop. 0.1 is unrepresentable in a fixed length binary string (it's a recurring number). Hence you aren't actually adding 0.1 but a value very close to 0.1 every time. This means it is possible that your counter never actually reaches exactly 3.1f


Advertisement