Thread: Reading from a file, got garbage instead

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    21

    Reading from a file, got garbage instead

    Just as a little test, I made a simple program that reads from a .txt file each line, and then stores whatever its between quotes on that line on a temporary string.

    Then, it writes every character on the line to another string until it finds the ending quote.

    Everything "seems" to go fine, as the compiler doesn't throw any errors, but whenever I run the program, after reading the lines, when it tries to output the lines to the screen, it instead shows a bunch of garbage.

    Here's the program
    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #define LINES 20
    #define MAXIMUMCHAR 30
    using namespace std;
    
    int main(){
        bool progfailed = false;
        ifstream archivo;
        archivo.open("probando.txt");
        string temporal;
        string *lines = new string[LINES];
        if(archivo.is_open()){
            while(!(archivo.eof())){
               for(int i = 1; i<LINES ; i++){                  //check each line 
                   getline(archivo,temporal);                  //pass the line to a temporal string
                   if(temporal[0]!='\"'){                      //check if the line begins with "
                     cout<<"Error on line "<<i<<": \'\"\' was expected on first character"<<endl;
                     } else {  
                        bool nextchar = true;                  //next character of the line
                        for(int j=1; j<MAXIMUMCHAR && nextchar == true; j++){
                            if(temporal[j]!= '\"' ){           //if line hasn't ended (there isn't a " )
                                (*(lines+i))[j] = temporal[j]; //write the char on the line string
                                } else {
                                cout<<"\nEnd of line "<<i<<" found\n";
                                nextchar = false;             //loop exit
                            }
                        }
                     }
                 }
             }
         } else {
         cout<<"File not found!"<<endl;
         progfailed = true;
    }  
    
    archivo.close();
    
    if(progfailed==false){                         //
    cout<<"Result:"<<endl;                         //
    for(int l=1; l<LINES ;l++){                    //if everything was succesful 
       cout<<"Line "<<l<<": "<<lines[l]<<endl;     //show the content of each line
    }
    }
    
    cout<<endl;
    cin.ignore();
    cin.get();
    return 0;
    }

    And here's the... uh... output... truncated of course, as it's a lot.

    Code:
    End of line 1 found
    
    End of line 2 found
    Error on line 3: '"' was expected on first character
    Error on line 4: '"' was expected on first character
    Error on line 5: '"' was expected on first character
    Error on line 6: '"' was expected on first character
    Error on line 7: '"' was expected on first character
    Error on line 8: '"' was expected on first character
    Error on line 9: '"' was expected on first character
    Error on line 10: '"' was expected on first character
    Error on line 11: '"' was expected on first character
    Error on line 12: '"' was expected on first character
    Error on line 13: '"' was expected on first character
    Error on line 14: '"' was expected on first character
    Error on line 15: '"' was expected on first character
    Error on line 16: '"' was expected on first character
    Error on line 17: '"' was expected on first character
    Error on line 18: '"' was expected on first character
    Error on line 19: '"' was expected on first character
    Result:
    Line 1: sfsdf es una lineaa\╪&= v98 NUMBER_OΦ&= OCESSORS=1 O°&= ndows_NT Pa'= \D
    evc\Bin;C:↑'= c\lib\gcc-li('= ngw32\3.2;C:8'= c\Bin;C:\DevH'= b\gcc-lib\miX'= 2\
    3.2;C:\Arch'= s de programx'= rland\Delphię'= n;C:\Archivo˙'=  programa\Boż'= d\
    Delphi7\Pr╕'= ts\Bpl\;C:\W╚'= WS\system32;    INDOWS;C:\W(=
       ........"esta es u A╪'= ♂   ........"esta es un  (= rchivos de programa\8(= ivos comu
    What is wrong here? I'd be grateful if someone could please take a look at it.

    Thanks in advance, and excuse my poor programming skills

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    >> (*(lines+i))[j] = temporal[j]; //write the ch

    The above is wrong for one thing. you can't add a character to std::string class like that. Suggest something like this:
    Code:
      lines[j] += temporal[j];

    >> string *lines = new string[LINES];
    why the dynamic memory allocation. std::string class is only a few bytes -- I think about 16 with my compiler. Hardly worth the problems associated with using new, unless the operating system you are using has a pretty small stack size.
    Code:
    string lines[LINES];

  3. #3
    C/C++ homeyg's Avatar
    Join Date
    Nov 2004
    Location
    Louisiana, USA
    Posts
    209
    I'm just wondering how the heck you can decipher your own code with a coding style like that..

  4. #4
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    Code:
    lines[j] += temporal[j];
    Just noticed -- variable j is being used for two entirely different purposes in the code above. The index number into array lines[] must not be the same variable as the index into the array temporal. One is pointing to an instance of a std::string object while the other is pointing to a specific character in the char array temporal.

  5. #5
    Registered User
    Join Date
    Feb 2006
    Posts
    21
    You added that to the code >.>
    Thanks Ancient Dragon, I removed the pointers (was trying to practice using them... but I always get errors when I do)

    And added some kind of "check" that only throws the line error if the line isn't empty

    It is a mess, but it works. And i didn't use any gotos, so i'm a bit proud of myself :')

    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #define LINES 10
    #define MAXIMUMCHAR 50
    using namespace std;
    
    int main(){
        bool progfailed = false;
        ifstream archivo;
        archivo.open("probando.txt");
        string temporal;
        string lines[LINES];
        for(int in = 1; in<LINES ; in++){
        lines[in] = "\0";
        }    
    
        if(archivo.is_open()){
            while(!(archivo.eof())){
               for(int i = 1; i<LINES ; i++){                   //check each line 
                   getline(archivo,temporal);                   //pass the line to a temporal string
                   if(temporal[0]!='\"'){                       //check if the line begins with "
                   if(temporal != "\0")cout<<"Error on line "<<i<<": \'\"\' was expected on first character"<<endl;
                   } else {  
                        bool nextchar = true;                  //next character of the line
                        for(int j=1; j<MAXIMUMCHAR && nextchar == true; j++){
                            if(temporal[j]!= '\"' ){           //if line hasn't ended (there isn't a " )
                                lines[i] += temporal[j];       //write the char on the line string
                                temporal = "\0";
                                } else {
                                if((lines[i]) != "\0"){
                                cout<<"End of line "<<i<<" found\n";
                                }
                                nextchar = false;             //loop exit
                            }
                        }
                     }
                 }
             }
         } else {
         cout<<"File not found!"<<endl<<"Creating file";
         ofstream nuevoarchivo("probando.txt");
         nuevoarchivo.close();
         progfailed = true;
    }  
    
    archivo.close();
    
    if(progfailed==false){                         //
    cout<<"\nResult:"<<endl;                       //
    for(int l=1; l<LINES ;l++){                    //if everything was succesful 
       if(lines[l] != "\0"){                       //verify the line isn't empty
       cout<<"Line "<<l<<": "<<lines[l]<<endl;     //show the content of each line
    }
    }
    }
    
    cout<<endl;
    cin.ignore();
    cin.get();
    return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  2. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 AM
  5. archive format
    By Nor in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 08-05-2003, 07:01 PM