Like Tree1Likes

C Stock Sorting Program Issue

This is a discussion on C Stock Sorting Program Issue within the C Programming forums, part of the General Programming Boards category; Hey guys, I'm new here and just started C this year in college. Next year I'm going to work on ...

  1. #1
    Registered User litebread's Avatar
    Join Date
    Dec 2011
    Location
    California
    Posts
    21

    Post C Stock Sorting Program Issue

    Hey guys, I'm new here and just started C this year in college. Next year I'm going to work on c++.

    To kick my first post of, I have a question. I receive an error message with Visual c++ 2008 Express in the savetext function. Look like this:
    Name:  error.jpg
Views: 350
Size:  64.5 KB

    Here's the code:


    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    /////////////////
    #define SIZE 2
    /////////////////
    struct Stock
    {
        char name[10];
        int numShares;
        float buyShare,currPrice,fees;
        float initCost,currCost,profit;
    };
    /* Load the data from the keyboard and calculates 
    the Initial Cost, Current Cost, and Profit 
    for each stock via an array */
    
    
    void load(struct Stock s[], int n) 
    {
        int i;
        for(i=0;i<n;i++)
        {
            printf("Enter the Stock Name\n");
            printf(">");
            gets(s[i].name);
            printf("Enter the Number of Shares\n");
            printf(">");
            scanf("%d", &s[i].numShares);
            printf("Enter the Buying Price Per Share\n");
            printf(">");
            scanf("%f", &s[i].buyShare);
            printf("Enter the Current Price Per Share\n");
            printf(">");
            scanf("%f", &s[i].currPrice);
            printf("Enter the Yearly Fees\n");
            printf(">");
            scanf("%f", &s[i].fees);
    
    
            s[i].initCost = (float)s[i].numShares * s[i].buyShare;
            s[i].currCost = (float)s[i].numShares * s[i].currPrice;
            s[i].profit = s[i].currCost - s[i].initCost - s[i].fees;
    
    
            fflush(stdin);
        }
    }
    
    
    /* Sort the array of structures 
    on stock name and print the array 
    after the sort is completed */
    
    
    void sort(struct Stock s[], int n)
    {
        Stock t;
        for(int i=0;i<n-1;i++)
            for(int j=0;j<n-1;j++)
                if(strcmp(s[j].name, s[j+1].name)>0)
                {
                    t=s[j];
                    s[j]=s[j+1];
                    s[j+1]=t;
                }
    }
    
    
    /* Calculate and print the total profit for all of the stocks. 
    That is, find the sum of the 5 profits for each stock. In 
    addition, find and print out the number of stocks that 
    had a positive profit, the number of stocks that had a 
    negative profit, and the number of stocks that broke 
    even, that is had a profit of $0.00 */
    
    
    void calc(struct Stock s[],int n)
    {
        float total=0;
    
    
        int Pos=0;
        int Neg=0;
        int Even=0;
    
    
        for(int i=0;i<n;i++)
        {
            total +=s[i].profit;
            if (s[i].profit>0)
                ++Pos;
            else
            if (s[i].profit<0)
                ++Neg;
            else
                ++Even;
        }
    
    
        printf("%d of stocks broke Positive\n",Pos);
        printf("\t%d of stocks broke Negative\n",Neg);
        printf("\t\t%d of stocks broke Even\n",Even);
        printf("\n");
        printf("The Total Trofit is $0.2%f\n", total);
    }
    
    
    void print(struct Stock s[], int n)
        {
            for(int i=0;i<n;i++)
            {
                printf("Your stock name is %s\n", s[i].name);
                printf("\tYour Initial cost is $%0.2f\n", s[i].initCost);
                printf("\t\tYour Current cost is $%0.2f\n", s[i].currCost);
                printf("\t\t\tAnd your Profit is $%0.2f\n", s[i].profit);
                printf("\n");
                printf("Good job! ");
            }
        }
    //Save the array of structures to a text file.
    void savetext(struct Stock s[], int n)
    {
        FILE *f;
        f = fopen("e:\final.txt", "w"); 
        int i;
        for(i=0;i<n;i++)
        {
            fprintf(f,"%s\n", s[i].name);
            fprintf(f, "%d  %f  %f  %f  %f  %f  %f\n", s[i].numShares, s[i].buyShare, s[i].currPrice, s[i].fees, s[i].initCost, s[i].currCost, s[i].profit);
        }
        fclose(f);
        fflush(stdin);
    }
    //Retrieve and print the text file.
    void loadtext(struct Stock s[], int n)
    {
        FILE *f;
        f = fopen("e:\final.txt", "r");
        int i;
        for(i=0;i<n;i++)
        {
            fgets(s[i].name, sizeof(s[i].name), f);
            fscanf(f,"%d%f%f%f%f%f%f\n", s[i].numShares, s[i].buyShare, s[i].currPrice, s[i].fees, s[i].initCost, s[i].currCost, s[i].profit);
        }
        fclose(f);
    }
    //Save the array of structures to a binary file.
    void savebin(struct Stock s[], int n)
    {
        FILE *f;
            f = fopen("e:\final.bin", "wb");
        fwrite(&s, sizeof(s[10]), n, f);
        fclose(f);
    }
    //Retrieve and print the binary file.
    void loadbin(struct Stock s[], int n)
    {
        FILE *f;
        f = fopen("e:\final.bin", "rb");
        fwrite(&s, sizeof(s[10]), n, f);
        fclose(f);
    }
    
    
    void main()
    {
        Stock s[SIZE];
        load (s, SIZE);
        sort (s, SIZE);
        savetext (s, SIZE);
        savebin (s, SIZE);
        print (s, SIZE);
        calc (s, SIZE);
        loadtext (s, SIZE);
        print (s, SIZE);
        loadbin (s, SIZE);
        print (s, SIZE);
        system("PAUSE");
    }
    You can also see it here on Pastebin.com: [C] csort_struct - Pastebin.com

    Thanks for help in advance!
    Attached Files Attached Files

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,295
    You know how it says "(Press Retry to debug the application)"? Well, click the Retry button. It will take you to the line of code that is the problem.
    Then load up the Call Stack window and find the function that called the one with the assert. Also load up the Autos or Locals window and you will be able to see the values of the variables that are relevant. You should see that your code is making a call to some standard library call and passing it a NULL pointer. For example calling fprintf with a NULL pointer may cause the problem.
    It's really quite easy to use the debugger. All those windows are easy to find in the Debug menu.
    Let us know if you're still stuck after that.

    Also note, do not do this:
    Code:
    fflush(stdin);
    That is undefinted behaviour and you are technically not alllowed to do that. Read the FAQs on this site for what you should be doing instead.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    In C, the '\' (backslash char), is an escape char, so strings with one \ in them, need to be doubled:
    Code:
    f = fopen("e:\final.txt", "w"); 
    
    should be:
    f = fopen("e:\\final.txt", "w"); 
    
    or more simply, use the more portable slash char:
    f = fopen("e:/final.txt", "w");
    Having a small function you could use to test whether the file was opened or not, would be a great thing to add to your program.

    If the file pointer receives NULL from fopen(), then the file was not opened, and your program needs to terminate.

  4. #4
    Registered User litebread's Avatar
    Join Date
    Dec 2011
    Location
    California
    Posts
    21
    This is what I'm getting after changing

    f = fopen("e:\final.txt", "w");

    to

    f = fopen("e:/final.txt", "w");

    Name:  error2.jpg
Views: 378
Size:  76.3 KBName:  error3.PNG
Views: 474
Size:  33.3 KB

    Its showing me something is wrong with this line:

    Code:
    fscanf(f,"%d  %f  %f  %f  %f  %f  %f\n", s[i].numShares, s[i].buyShare, s[i].currPrice, s[i].fees, s[i].initCost, s[i].currCost, s[i].profit);
    Also for

    fflush(stdin);

    Thats how me professor thought me at college. Whats wrong with it?

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    As the error shows, you're trying to write to a location that is invalid.

    fflush(stdin), used to work (sort of), on some compilers, years ago. It was heavily used by Turbo C help files and example programs. But it never worked reliably, and the C standard (when it came into being), wanted nothing to do with it.

    So fflush() only works on OUTward streams, not on incoming streams, like stdin. The way I think of it is, it's like flushing in your home - you flush the toilet, but you don't flush the kitchen sink.

    If you have a newline waiting in the input stream, there are a few ways to handle it:

    getchar() - removes one char from the input stream
    while((charname=getchar()) != '\n') - removes all chars including the first newline char.

    scanf(" %c", &charName) - the space in the format string instructs scanf() to skip the first char in the input stream.

    You should be checking every file you open to be sure it's given a valid file handle by fopen().

    Questions:
    1) Are you getting any compiler warnings or errors?

    2) Or is it just a run-time failure, without either warnings or errors?

    Post up your latest version and a small amount of data that I can enter to see the error, and I'll take a look at it.

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by litebread View Post
    This is what I'm getting after changing

    f = fopen("e:\final.txt", "w");

    to

    f = fopen("e:/final.txt", "w");

    Name:  error2.jpg
Views: 378
Size:  76.3 KBName:  error3.PNG
Views: 474
Size:  33.3 KB

    Its showing me something is wrong with this line:

    Code:
    fscanf(f,"%d  %f  %f  %f  %f  %f  %f\n", s[i].numShares, s[i].buyShare, s[i].currPrice, s[i].fees, s[i].initCost, s[i].currCost, s[i].profit);
    Also for

    fflush(stdin);

    Thats how me professor thought me at college. Whats wrong with it?
    Take the \n out... you don't want that on input functions.

  7. #7
    Registered User litebread's Avatar
    Join Date
    Dec 2011
    Location
    California
    Posts
    21
    Quote Originally Posted by Adak View Post
    As the error shows, you're trying to write to a location that is invalid.

    fflush(stdin), used to work (sort of), on some compilers, years ago. It was heavily used by Turbo C help files and example programs. But it never worked reliably, and the C standard (when it came into being), wanted nothing to do with it.

    So fflush() only works on OUTward streams, not on incoming streams, like stdin. The way I think of it is, it's like flushing in your home - you flush the toilet, but you don't flush the kitchen sink.

    If you have a newline waiting in the input stream, there are a few ways to handle it:

    getchar() - removes one char from the input stream
    while((charname=getchar()) != '\n') - removes all chars including the first newline char.

    scanf(" %c", &charName) - the space in the format string instructs scanf() to skip the first char in the input stream.

    You should be checking every file you open to be sure it's given a valid file handle by fopen().

    Questions:
    1) Are you getting any compiler warnings or errors?

    2) Or is it just a run-time failure, without either warnings or errors?

    Post up your latest version and a small amount of data that I can enter to see the error, and I'll take a look at it.
    Ok will fix that in the future. Just trying to get this to run.

    Its a run time failure. I'm using Visual c++ 2008 Express.

    I attached the .cpp file. Any info can do. Just run debug and you will get the promts for data. All you need is a name for the stock, four int variables (four numbers) and one float variable. This variables can be any number you want them to be,a nd the name an be random too, just for testing. The only thing that can make a difference is using the same name twice. This will cause strcmp in sort to derp.....
    Attached Files Attached Files

  8. #8
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I have Pelles C, and Pelles C is for C only and Windows only.

    Please, before we waste any time on it, compile it with your C NOT YOUR C++ compiler, and then see what happens.

    And please, don't come into this forum with C++ files, or using a C++ compiler. We have a very capable and active C++ forum for that.

    C and C++ are NOT the same language, at all. What is a "derp..."?

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Everywhere you declare a Stock struct in your program, you need to have:

    struct Stock nameofStockInstance;

    The keyword "struct" is essential, and your compiler should be giving you multiple messages about "undeclared identifier 'Stock'", or words close to that.

    I can't believe you ever were able to compile this program, at all - I've got about 14 errors stopping me from compiling it, atm.

    void main() is never OK. It's either:

    int main(void) or int main(int argc, char *argv[])

    and in either case, has a required return of 0 (for normal termination of the program), or any other integer for any of various abnormal terminations of the program.

    Either way, the operating system will be expecting SOME integer message from the program, upon termination.
    Last edited by Adak; 12-08-2011 at 06:39 PM.

  10. #10
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,295
    Quote Originally Posted by litebread View Post
    This is what I'm getting after changing

    f = fopen("e:\final.txt", "w");

    to

    f = fopen("e:/final.txt", "w");
    I would actually go with the double backslash, otherwise you'll perhaps run into problems again later if you start using the Win API directly.
    Unless of course you're just as likely to go an use linux...

    Its showing me something is wrong with this line:

    Code:
    fscanf(f,"%d  %f  %f  %f  %f  %f  %f\n", s[i].numShares, s[i].buyShare, s[i].currPrice, s[i].fees, s[i].initCost, s[i].currCost, s[i].profit);
    Well what it will be showing you is that f is NULL. That means the file was not opened succesfully.
    You should start by adding error handling to the code. I.e. do something else like showing an error if the file could not be opened.

    Also for

    fflush(stdin);

    Thats how me professor thought me at college. Whats wrong with it?
    Perhaps if I give you a direct link to the relevant FAQ entry then you'll be more likely to have a read: Cprogramming.com FAQ > Why fflush(stdin) is wrong
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  11. #11
    Registered User litebread's Avatar
    Join Date
    Dec 2011
    Location
    California
    Posts
    21
    Quote Originally Posted by iMalc View Post
    Well what it will be showing you is that f is NULL. That means the file was not opened succesfully.
    Well i need it to be opened and saved. The data has to be saved to a .txt and a .bin for this project, which means f can not be null. I know what you are talking about (Something like an if data is missing printf("Error. Can not open file"), but I need the files to be opened and saved.

    I'm on windows, and I made sure perms are working fine. As a matter of fact, it writes to disk, but gives me the error when it tries to open the file .....

  12. #12
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by litebread View Post
    Well i need it to be opened and saved. The data has to be saved to a .txt and a .bin for this project, which means f can not be null. I know what you are talking about (Something like an if data is missing printf("Error. Can not open file"), but I need the files to be opened and saved.

    I'm on windows, and I made sure perms are working fine. As a matter of fact, it writes to disk, but gives me the error when it tries to open the file .....
    First of all the \ used by windows as a path separator is also the escape character used by C when formatting text.

    Does Not Work ... char *file = "e:\fred.txt";
    Does So Work ... char *file = "e:\\fred.txt";

    Secondly that gang at Microsoft just loves to keep us guessing...

    Open Control Panel -> Folder Options -> View tab -> uncheck "Hide extensions of known file types".
    OK your way out.

    I'd almost bet your file is named something like "fred.txt.txt" or such...

    Oh... and huge mistake on Windows ... don't mess with file permissions. More than one perfectly good hard disk has been rendered inaccessible because of permissions gone wrong. The defaults will go fine.

  13. #13
    Registered User litebread's Avatar
    Join Date
    Dec 2011
    Location
    California
    Posts
    21
    Quote Originally Posted by CommonTater View Post
    First of all the \ used by windows as a path separator is also the escape character used by C when formatting text.

    Does Not Work ... char *file = "e:\fred.txt";
    Does So Work ... char *file = "e:\\fred.txt";

    Secondly that gang at Microsoft just loves to keep us guessing...

    Open Control Panel -> Folder Options -> View tab -> uncheck "Hide extensions of known file types".
    OK your way out.

    I'd almost bet your file is named something like "fred.txt.txt" or such...

    Oh... and huge mistake on Windows ... don't mess with file permissions. More than one perfectly good hard disk has been rendered inaccessible because of permissions gone wrong. The defaults will go fine.
    Actually I always had the full file type extension shown on my PC. (I'm also a linux user, and I can't stand not seeing the extensions on my files. I even put the task bar to the top for kicks.) And as far as I have checked it looks fine. Both files (.txt and .bin are there and named as they should, both contain the data entered. But it wont read those files properly. I put the entire path to the files and still it just wont work.

    as for the perms I didnt mess with them. Everything is how it should be.

  14. #14
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Well, there's also this in your original message...
    Code:
    //Retrieve and print the binary file.
    void loadbin(struct Stock s[], int n)
    {
        FILE *f;
        f = fopen("e:\final.bin", "rb");
        fwrite(&s, sizeof(s[10]), n, f);
        fclose(f);
    }
    1) you need to double thos slashes ...
    2) you need to check if it actually opened or not...
    3) writing to a file you're trying to read ain't gonna work...
    4) size of s[10] isn't going to give you what youwant there...

    Code:
    void loadbin(struct Stock *s, int n)
    {
        FILE *f;
        f = fopen("e:\\final.bin", "rb");
        if (! f)
          { printf("Could not open the file");
             exit(1); }
        fread(s, sizeof(struct stock), n, f);
        fclose(f);
    }
    iMalc likes this.

  15. #15
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,295
    Quote Originally Posted by litebread View Post
    Well i need it to be opened and saved. The data has to be saved to a .txt and a .bin for this project, which means f can not be null. I know what you are talking about (Something like an if data is missing printf("Error. Can not open file"), but I need the files to be opened and saved.
    None of what you just said changes anything. You need to check for the file not opening. If it fails, display an error and then exit.
    f can and will be null for whatever reason the OS chooses. Putting your head in the sand and pretending it is not so, will simply lead to your program crashing.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sorting issue
    By Ssalty in forum C++ Programming
    Replies: 1
    Last Post: 05-18-2011, 10:03 AM
  2. Stock Data
    By bskaer1 in forum C++ Programming
    Replies: 0
    Last Post: 10-16-2010, 11:59 PM
  3. compare issue while sorting
    By Micko in forum C++ Programming
    Replies: 1
    Last Post: 03-06-2004, 09:34 AM
  4. Stock market
    By Liger86 in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 05-20-2003, 05:12 PM
  5. Stock Taking program
    By C Babe in forum C++ Programming
    Replies: 3
    Last Post: 05-15-2003, 07:40 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21