Results 1 to 16 of 16
  1. #1
    Join Date
    Aug 2007
    Location
    Leeds
    Posts
    77

    C question: problem with for loop

    Hi - I'm doing some C programming related to mathematics. I want the user to enter pairs of x and y values, and unspecified number of pairs, and to press f when they are finished. However, my for loop does not seem to work. When I execute the prog it runs, but when I put in f, the console goes crazy with print.

    I would appreciate it if somebody could point me in the right direction.



    #include <stdio.h>
    #include <stdlib.h>



    int main()
    {
    float x_values[50];
    float y_values[50];
    char suc_x,suc_y;

    int i,j,size=0;



    printf("You are about to enter pairs of x and y values.\n");
    printf("Press f when you have finished.\n");

    for(i=1;suc_x!='f';i++)
    {
    printf("x%d = ", i);
    suc_x=scanf("%f",&x_values[i]);
    printf("y%d = ", i);
    suc_y=scanf("%f",&y_values[i]);

    size=size+1;

    }

    system("cls");

    for(j=1;j<=size;j++)
    {
    printf("%f\t%f",x_values[j],y_values[j]);
    }

    return 0;


    }

  2. #2
    Join Date
    Aug 2007
    Location
    Greece
    Posts
    390
    Do it in a while loop.
    Code:
    while (suc_x!='f')
    {
    }
    NOT a webhost!helping here just for the fun of it!
    G(r)eek inside.

  3. #3
    Join Date
    Feb 2006
    Location
    Kusadasi, Turkey
    Posts
    3,273
    scanf doesn't return a pressed character. It returns the number of characters read. http://www.cplusplus.com/reference/c...dio/scanf.html

    So you should check x_values[i] variable, not suc_x.
    Fraud Record - Stop Fraud Clients, Report Abusive Customers.
    █ Combine your efforts to fight misbehaving clients.

    HarzemDesign - Highest quality, well designed and carefully coded hosting designs. Not cheap though.
    █ Large and awesome portfolio, just visit and see!

  4. #4
    Join Date
    Aug 2007
    Location
    Leeds
    Posts
    77
    Thanks for your help, tix3 - I'll try the while loop.

    And thanks, Harzem. This is a C prog though, not C++, so does that effect the scanf?

  5. #5
    Join Date
    Feb 2006
    Location
    Kusadasi, Turkey
    Posts
    3,273
    Quote Originally Posted by telegraph_hill View Post
    Thanks for your help, tix3 - I'll try the while loop.

    And thanks, Harzem. This is a C prog though, not C++, so does that effect the scanf?
    While loop won't help actually And no, C and C++ is the same for scanf.
    Fraud Record - Stop Fraud Clients, Report Abusive Customers.
    █ Combine your efforts to fight misbehaving clients.

    HarzemDesign - Highest quality, well designed and carefully coded hosting designs. Not cheap though.
    █ Large and awesome portfolio, just visit and see!

  6. #6
    Join Date
    Aug 2007
    Location
    Leeds
    Posts
    77
    That's true - the while loop did not make any difference - same thing happening.

  7. #7
    Hello,

    I'm going to try and be as easy going as possible but there are so many errors there it could take some time.

    Firstly, if you can specify any number of pairs, and any number can be greater than 50, then your static arrays are going to overflow. That is such a huge security issue you should get out of that habit even where it might not matter so much.

    In C arrays are 0 based, so the loops really should start from 0 if you are going to have access to all 50 values, if you start from 1 you can only use 49 of them.

    printf doesn't promise to send anything to the screen, and typically won't until you send a newline, so you should flush those prompts.

    Read up on scanf, its return is the number of inputs successfully scanned. When you enter 'f' it will return 0 because it can't parse 'f' as a float. This is why you get an infinite loop as it keeps on seeing the 'f' it gave up on last time through the loop.

    system("cls") is just awful, but at least it might work sometimes.

    The last printf should probably have a '\n' at the end for readable output.

    I hope that that is enough to be getting on with, some ideas at least. Do you have to use C? C++ is far more convenient for handling dynamic arrays, and Python is far more convenient for everything. If you could just use glib that would be a huge advantage, any chance?

    I'll spend a little time preparing some corrected code...

    Cheers,

    Jim
    Blue Room Hosting - High availability UK VPS
    KVM Plans - Multiple OS support. Virtual console and CD drive.

  8. #8
    Join Date
    Aug 2007
    Location
    Leeds
    Posts
    77
    Thanks, Jim - that's something to think about.

    Yes - I have to use C. I am doing a module on it at university as part of a physics course. It's a v basic intro to C.

    I am not expecting more than 50 pairs - so that probably isn't a problem from my point of view. I just have to show some post-grads that I can get this program to work.

    How would you get the user to indicate that the pairs have all been entered, so the prog can perform the next part?

  9. #9
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        float x_values[50];
        float y_values[50];
    
        int i, size=0;
    
        printf("You are about to enter pairs of x and y values.\n");
        printf("Press f when you have finished.\n");
    
        for (i=0; ; i++)
        {
            printf("x%d = ", i + 1);
            fflush(stdout);
    
            /* try and parse a float */
            if (scanf("%f", &x_values[i]) != 1)
            {
                /* should have entered 'f' */
                if (fgetc(stdin) != 'f')
                {
                    printf("Press f when you have finished.\n");
                    continue;
                }
                else break;
            }
    
            printf("y%d = ", i + 1);
            fflush(stdout);
    
            /* try and parse a float */
            if (scanf("%f", &y_values[i]) != 1)
            {
                /* should have entered 'f' */
                if (fgetc(stdin) != 'f')
                {
                    printf("Press f when you have finished.\n");
                    continue;
                }
                else break;
            }
    
            ++size;
    
            if (size >= 50)
            {
                printf("Ran out of room.\n");
                break;
            }
        }
    
        printf("\n\n");
    
        for(i=0; i<size; i++)
        {
            printf("%f\t%f\n", x_values[i], y_values[i]);
        }
    
        return 0;
    }
    That should handle most common conditions but the input handling is still a little lax IMO.

    Hope it makes sense.

    Jim
    Blue Room Hosting - High availability UK VPS
    KVM Plans - Multiple OS support. Virtual console and CD drive.

  10. #10
    Join Date
    Aug 2007
    Location
    Leeds
    Posts
    77
    Wow - thanks, Jim. I'm going to give that a go, and I'll let you know how I get on.

    Carol

  11. #11
    Join Date
    Aug 2007
    Location
    Leeds
    Posts
    77
    That really does work, Jim - thanks.

    I'm now going to go over it and learn some of these functions I was unaware of.

  12. #12
    You are welcome,

    Some other less important things come to mind. Firstly storing the points in two separate arrays isn't quite as neat as declaring a point struct and having a single array:

    Code:
    typedef struct
    {
      float x;
      float y;
    } Point;
    
    ...
      Point points[50];
      ...
      scanf("%f", &(points[i].x))
    Secondly, data entry from the command line is a huge drag. It is much better to put the data in a file and read from that. This will require fopen, fscanf and fclose and very little change to your code.

    Thirdly, 50 might seem like enough, but programmers have been getting that wrong for years, considering how little memory usage is involved why not make it 50k and be a thousand times more sure?

    I hope the rest of the project goes well,

    Best Wishes,

    Jim
    Blue Room Hosting - High availability UK VPS
    KVM Plans - Multiple OS support. Virtual console and CD drive.

  13. #13
    Join Date
    Aug 2007
    Location
    Leeds
    Posts
    77
    Thanks, Jim - those are some points to ponder.

    Yes, doing it as a single array would be neater.

    I used to be fairly ok at C++, didn't do it for a few years, and now doing this short course in C. We haven't covered much, and thus far the exercises have been v simple. Then suddenly we get this.

    I don't think we've been given enough repertoire to do it.

    Still - I'll bash on with it tomorrow - there's some good mathsy stuff next.

  14. #14
    Join Date
    Aug 2007
    Location
    Leeds
    Posts
    77
    If you happen to be online, Jim, or anyone else:

    what specifically does

    fflush(stdout);

    do?

  15. #15
    FILE pointers have (or at least can have) a character buffer. So when you
    Code:
    printf("something");
    which is equivalent to
    Code:
    fprintf(stdout, "something");
    the text can be kept in stdout's buffer and not sent to the underlying device, which in this case is probably the screen.

    The default setup of the buffers depends on your OS, I know that on Linux the output streams are line buffered by default, so it automatically flushes every time it sees a newline. If you want to be sure that a prompt is sent to the screen it is best to use fflush to make sure, otherwise your program will break in alien environments.

    Just a good habit to get into really.

    Cheers,

    Jim
    Blue Room Hosting - High availability UK VPS
    KVM Plans - Multiple OS support. Virtual console and CD drive.

  16. #16
    Join Date
    Aug 2007
    Location
    Leeds
    Posts
    77
    Thanks, Jim. So really it's just a case of good habits. Thanks.

    Another thing I've been racking my brain about and googling is parsing - I'm not sure what this means.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •