dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 21

Thread: code problem

  1. #1
    Join Date
    Jul 2007
    Posts
    33

    code problem

    Hi everybody!
    This is my first time on this forum. I'm a novice, and I'm looking for help regarding a section of code in a c++ program that I wrote recently. I'm aggravated because I've written everything correctly (as far as I know) and the program still stops at the same place every time.

    Could the problem be with my compiler (Dev c++) or is there in fact something wrong with the way that I've written the code?

    This is the block of code that is the problem. It is the first half of a function (doc()). There is a while() condition in the function that is always fulfilled, though the contents of the while() block should cause it to end when the string "/*" is found in the file "hscene.txt". However, '/' is never reached in the file and char test[12] is never defined (When the program is run, there is only a blinking cursor in the top-left corner of the screen). I know that the file "hscene.txt" is accessible and that it does contain the string constant searched for by object.ignore();

    void doc() //defines the number of points (pint) and the object coordinates (obj)
    {ifstream object("hscene.txt"); //opens hscene.txt for reading
    char test[12];
    int y, x=1;
    while(x)
    {object.ignore(EOF,'/'); //finds a slash in the file
    object.seekg(-1); //goes back before the slash
    object.getline(test,3,'\0'); //recieves the next two characters in the file (hopefully "/*")
    if(!strcmp(test, "/*"))x=0;} //verifies that test equals the desired string and ends the loop

    This is my first time posting code questions on the internet, so if you need more info about the program, please ask me.

    Thank you very much for reading my question.
    Andy

  2. #2
    Join Date
    Mar 2007
    Location
    Montreal, Quebec, Canada
    Posts
    185

    Re: code problem

    OK, so you have a few problems here.

    The first is with object.ignore. The first parameter is the number of characters to ignore, so you have to pass a big number if you want it to scan until the end of the file. You can use numeric_limits<int>::max() if you want to scan until the end.

    The second problem is with object.seekg(). If you just pass one parameter, then it will treat it as a position. That's bad if you're passing -1, since there is no position -1.
    If you pass 2 parameters, the second parameter tells what you're searching relative to. If you pass ios_base::cur, then it means you're searching relative to your current position (which is what you're trying to do).

    The third is that you should use code tags (code and /code with square brackets around them) when displaying code, as it makes it easier for the rest of us to read. I believe some people won't even bother reading it if it isn't nicely formatted.

    Here is what your function should look like:
    Code:
    void doc() //defines the number of points (pint) and the object coordinates (obj)
    {
        ifstream object("hscene.txt"); //opens hscene.txt for reading
        char test[12];
        int y, x=1;
        while(x)
        {
            object.ignore(numeric_limits<int>::max(), '/'); //finds a slash in the file
            object.seekg(-1, ios_base::cur); //goes back before the slash
            object.getline(test,3,'\0'); //recieves the next two characters in the file (hopefully "/*")
            if(!strcmp(test, "/*"))
                x=0;
        } //verifies that test equals the desired string and ends the loop

  3. #3
    Join Date
    Jul 2007
    Posts
    33

    Re: code problem

    Wow, IC...
    Thanks a lot! You were right on about the EOF replacement, format errors, etc. That's what I get for using sketchy internet c++ resources. I guess I need to keep in mind that programming code standards do change over time, and that not all c++ resources are up to date. Every problem that you help me with is one that I will never have to worry about again.

    The next problem relates to object.getline(...) in the same section of code.
    At the line, object.seekg(...), the input pointer is at 304 (the correct place). After the next line, object.getline(...), the input pointer is at 318, and test does not recieve the next 2 characters.

    I think that I may be using getline incorrectly; However, I've tried using object.read() instead (without the delimiter), but I have the same problem.

    Code:
    void doc()  //defines the number of points (pint) and the object coordinates (obj)
         {ifstream object("hscene.txt");
         char test[12];
         int y, x=1;
         while(x)
                 {object.ignore(numeric_limits<int>::max(),'/');
                 x=0;
                 ct(test);      //nullifies char test[12]
                 object.seekg(-1,ios_base::cur);
                 object.getline(test,2,' ');
                 if(!strcmp(test, "/*"))x=0;}
    Thanks again, Illegalcharacter!
    Your previous help was invaluable.

    Andy

  4. #4
    Join Date
    Mar 2007
    Location
    Montreal, Quebec, Canada
    Posts
    185

    Re: code problem

    With getline you need to remember that it only extracts the number you put in minus one. You're putting in 2, but since you're looking for a "/*" then you'll want to put in 3 (I believe this is because getline tacks on the '\0' at the end of the string).

    Here's the code that I tried here:
    Code:
    char test[10];
    object.getline(test, 3);
    This successfully found any /*'s in the file.

  5. #5
    Join Date
    Jul 2007
    Posts
    33

    Re: code problem

    Yeah, I'd already changed that 2 into a 3 before posting that last message (sorry about that). That while block works now, but I had to change object.seekg(-1, ...) to object.seekg(-7, ...); I dont know why that was necessary, but it apparently was.

    I put the char test[12] definition into the while statement so that each new test[12] is empty/fresh. I also added ct() (which nullifies test[12]) for the same reason.

    Well, the following code is a different block of the same function (same ol' problems). I don't get it: char test[12] is never defined by object.getline for some reason. I tried using object.tellg() to find out where the input pointer is in the file, but it only returns -1 over and over again (which I know is an error).
    How is this code wrong? The problems seem to be very repetitive...

    Code:
    while(x)
                 {char test[12];
                 object.ignore(numeric_limits<int>::max(),'p');
                 ct(test); cout<<object.tellg();
                 object.seekg(-1,ios_base::cur);
                 object.getline(test,9);cout<<test;
                 if(!strcmp(test, "points {"))x=0;}
    Thanks again for your help!
    Andy

  6. #6
    Join Date
    Jul 2007
    Posts
    33

    Re: code problem

    As far as my last post: forget it. I figured it out (though it's a very ugly fix).

    First of all, whenever I used object.getline() the input pointer location would be lost somehow. However, that does not occur when I use object.get(). However, the input pointer does still end up in weird locations, so I end up having to change the object.seekg(-1, ...) to object.seekg(-9, ...) to get the input pointer back where it should be.

    I havn't reached the next problem in the program code yet, but when I do, I'll post it. The important thing for me is that I'm past the point of using fstream functions, so I won't have any more problems with that...

    Thanks again for all of your help and support!
    Andy

  7. #7
    Join Date
    Jul 2007
    Posts
    33

    Re: code problem

    I'm having more trouble with seekg().
    I think I'm having the same problem as this guy:

    http://www.velocityreviews.com/forum...text-file.html

    I'm glad I found this thread because the person who wrote it seems to be able to explain the problem better than I can. My program is not as advanced as his, but the problem seems to be of a very similar nature.

    However, I still don't know the solution...
    Please help.

    Thanks.
    Andy

  8. #8
    Join Date
    Mar 2007
    Location
    Montreal, Quebec, Canada
    Posts
    185

    Re: code problem

    Hmm, I'm no expert on streams, however it sounds like you've got quite a problem here. I'm not sure why things are working the way they are, but one fix I can suggest is instead of using the stream, you can just load everything into a string and deal with it from there. A way you can do this is like so:
    Code:
    int c;
    string file;
    while ( (c = object.get()) != -1)
        file += (char)c;
    Strings are a lot easier to work with than files, so you won't have nearly as much trouble with things like seekg() and tellg().

  9. #9
    Join Date
    Apr 2004
    Location
    Canada
    Posts
    1,342

    Re: code problem

    I don't know if this is what's causing your problems, but I was taught that in order for seekg()/tellg() to work properly, you need to open your file in random-access mode, which means using the 'in' and 'out' flags at the same time:

    Code:
    ifstream object("hscene.txt", std::ios_base::in | std::ios_base::out);
    Hmm, I'm no expert on streams, however it sounds like you've got quite a problem here. I'm not sure why things are working the way they are, but one fix I can suggest is instead of using the stream, you can just load everything into a string and deal with it from there. A way you can do this is like so:

    Code:
    int c;
    string file;
    while ( (c = object.get()) != -1)
        file += (char)c;
    Strings are a lot easier to work with than files, so you won't have nearly as much trouble with things like seekg() and tellg().
    I like the idea of reading the whole file at once, then working with a string, but appending to a string character by character is very inefficient - for a large input file, it can cause a lot of memory reallocations in the string, which take time.

    This way is a little better:
    Code:
    ifstream object("hscene.txt", std::ios_base::in | std::ios_base::out | ios_base::ate);  // 'ate' flag means bring the file pointer to the end of the file
    int file_size = object.tellg();  // determine file size
    object.seekg(0);  // go to beginning of file
    string file(file_size, '\0');  // pre-allocate required length of string
    for (int i = 0; i < file_size; ++i)
        file[i] = object.get();
    And this way even better because it does the reading in one operation (although it requires two allocations of the space needed to store the file rather than one):
    Code:
    ifstream object("hscene.txt", std::ios_base::in | std::ios_base::out | ios_base::ate);  // 'ate' flag means bring the file pointer to the end of the file
    int file_size = object.tellg();  // determine file size
    object.seekg(0);  // go to beginning of file
    vector<char> buffer(file_size);  // temporary storage
    object.read(&buffer[0], file_size);  // read file into temporary storage
    string file(&buffer[0], &buffer[0] + buffer.size());  // copy into a string
    You can't read the whole file directly into a string in one read operation without an ugly const_cast which is better avoided.
    Old Unix programmers never die, they just mv to /dev/null

  10. #10
    Join Date
    Jul 2007
    Posts
    33

    Re: code problem

    Wow!
    I didn't know about the string class. I had to look it up, but it didn't take me long to long to realize its purpose. Otherwise, I'd say you're right, Illegal Character: "Downloading" the contents of the file is the best solution.

    Now that I look into it, the string class has so many useful functions (find(), etc.) and will make program manipulation so much easier.
    I'm sad that I'll have to rewrite a lot of the problematic code but, if it makes it that much easier, it will be worth it.

    High Commander 4,
    I'll try to use the code you posted as examples. I don't know if I'll be able to use the last example since I don't really understand much of it (vector<char>, buffer(), etc...).
    Also, when I define the string, why do I have to preallocate space for the string. I thought you didn't have to define the length of a string.

    A few other questions:
    How are the operators += and + different for strings?
    Also, what does the line, while ( (c = object.get()) != -1), mean? Does it have something to do with npos?

    Anywho...
    Troubleshooting this program has truly been a learning experience.
    I think that this solution will solve my problem completely.
    Thank you so much for your ingenuitive ideas!
    Andy
    Last edited by hixidom; July 12th, 2007 at 09:54 PM.

  11. #11
    Join Date
    Jul 2007
    Posts
    33

    Re: code problem

    Well, I made a new function to put the contents of the file into a string:

    Code:
    void fdownload()
         {ifstream object("hscene.txt", std::ios_base::ate);
         int x, filesize=object.tellg();
         object.seekg(0);
         for(x=0; x<filesize; x++)
                 {object.get(file[x]);}
         object.close();}
    However, although there are about 1800 bits in the file, the 'for' statement stops at x=32, an error appears, and the program terminates.

    I'm not sure what the problem is. I left out the -in and -out flags for now because they didn't effect whether or not the error occurred. object.tellg() returns the correct value. object.seekg(0) is not the problem. I've tried different forms of the object.get() line but without any new results. I checked the max_capacity of file (the string variable), but there was plenty of space.

    Basically, I've gone from one problem right into another. Again, the syntax appears to be perfect, yet the program fails!

    Question: How is x++ different from ++x ?
    Thanks;
    Andy

  12. #12
    Join Date
    Apr 1999
    Posts
    27,449

    Re: code problem

    Quote Originally Posted by hixidom
    Well, I made a new function to put the contents of the file into a string:
    I would highly suggest you create a simple program to read in the file, and post it. Right now, we have bits and pieces of things you have or have not done, and it is very hard to follow what you're doing.

    First, we don't know what "file[x]" is in the loop. Second, we don't know what the file you're reading contains. And last, we don't know where, when, or how you are calling this function.

    A simple example:
    Code:
    #include <fstream>
    
    void ReadTheFile()
    {
        // code to read the file
    }
    
    int main()
    {
         ReadTheFile();  // reads the file
    }
    Add code to make sure that this compiles and links correctly. Also if possible, zip up the data file that you're supposed to be reading. Then everyone with a compiler can test your code and give you the correct solution, instead of trying to guess what to do.

    Also, there have been many new posters looking for help, and respond "they did this" and "they did that". It is only when they are prodded to actually post the code, they didn't do what they stated they did (because they either didn't realize it, or for some other reason). By posting a compilable, but small example, everyone will know what's what, and eliminates us from barking up wrong trees.
    Basically, I've gone from one problem right into another. Again, the syntax appears to be perfect, yet the program fails!
    Follow these guidelines:

    http://www.parashift.com/c++-faq-lit...t.html#faq-5.8
    Question: How is x++ different from ++x ?
    One is post-increment and one is pre-increment. It should be discussed in any C++ book that you're using, since it is a fundamental part of the language.

    Regards,

    Paul McKenzie

  13. #13
    Join Date
    Jul 2007
    Posts
    33

    Re: code problem

    Sorry Paul; I asked about forum format in my first post.
    Anywho...

    Code:
    //compiler:  Dev-C++
    #include<iostream>
    #include<fstream>
    #include<string>
    using namespace std;
    
    string file;
    
    void fdownload()
         {ifstream object("hscene.txt", std::ios_base::ate);
         int x, filesize=object.tellg();
         object.seekg(0);
         for(x=0; x<filesize; x++)
                 {file[x]=object.get();}
         object.close();}
                                 
    int main()
        {fdownload();
        return 1;}
    I guess this code should demonstrate my problem. I'm a little confused because, although the code is almost identical here and in the original program, this section of code exhibits a different problem (input pointer always == -1).
    I've attached the file that is being read in a zip file. Though it is an .an8 file, it can generally be treated as a .txt file. I've changed the code in the program from "hscene.txt" to "hscene.an8", but it doesn't make a difference anyway.

    If there's any more info that I can add, please alert me!

    Thank you.
    Andy
    Attached Files Attached Files

  14. #14
    Join Date
    Nov 2006
    Location
    Essen, Germany
    Posts
    1,344

    Re: code problem

    You´re tyring to read a binary file into a string, that might be a problem since you don´t set the string length appropriately. Try using a vector:

    Code:
    #include <vector>
    #include <iostream>
    #include <fstream>
    
    //vector to hold file data
    std::vector<char> FileBuffer;
    
    
    void fdownload()
    {
       // open file
       std::ifstream file_stream("hscene.txt", std::ios_base::ate);
    
       // determine file size
       int iFilesize = file_stream.tellg();
       file_stream.seekg(0);
       
       // resize vector to hold N elements
       FileBuffer.resize( iFileSize );
    
       // read whole file at once
       file_stream.read( &FileBuffer[0], iFileSize );
    
       // close file
       file_stream.close();
    }
                                 
    int main()
    {
       fdownload();
       return 1;
    }
    That´s how I read in small files. However, there´s only one thing I´d like to improve: vector.resize() calls the type´s constructor for each element, whereas reserve() allocates an uninitialized block of memory without setting the vector´s size. Is it possible to allocate an uninitialized block of memory AND setting the vector´s size?

  15. #15
    Join Date
    Jul 2007
    Posts
    33

    Re: code problem

    I'll try the vector code.
    However, I'd like to use a string if possible. Perhaps I can transcribe from the final vector to a string.

    Also, in the last program that I posted, the problem occurred before the string was even reached. Thus, I don't think that the problem has to do with the type of variable that the file is downloaded to.

    On the other hand, I don't know anything.

    Thank you for your help!
    Andy

Page 1 of 2 12 LastLast

Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)