reading from file

*Sigh*, i have no idea why the while() part below doesn't work
(only always the first set was being read) (1, The C++ Programming Lang, Bjarne Stroustrup)

This is what the file looks like :
1
The C++ Programming Language
Bjarne Stroustrup
2
The C Programming Language
Brian Kerninghan, Dennis Ritchie
3
Head First Java
Oreilly Media


And this is the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
    // ...
    static Book book[ MAX_BOOKS ]; // I know i should have use std::vector
    size_t tempBookId;
    char tempTitle [ MAX_CHAR ]; // yeah, i know i should have use std::string
    char tempAuthor[ MAX_CHAR ];

    size_t i = 0;

    // This loop isn't working : (i have no idea why)

    while( fileIn >> tempBookId &&
           fileIn.ignore() &&
           fileIn.getline( tempTitle, MAX_CHAR ) &&
           fileIn.getline( tempAuthor, MAX_CHAR ) )
    {
        book[ i ].bookId = tempBookId;
        strncpy( book[ i ].title,
                 tempTitle,
                 MAX_CHAR );
        strncpy( book[ i ].author,
                 tempAuthor,
                 MAX_CHAR );
        i++;
    }
    // ...
    return book;
Last edited on
bump
Have you tried without the ignore()? The getline() function skips leading whitespace characters by default.

If that doesn't work, try printing out all three of your temp??? variables and see which ones look incorrect.

Why are you using the temp variables instead of just retrieving the values into the structure variables?

wow, it worked when i directly copied the extracted values and didn't use the temporary variables.

Although i'm still wondering why the original code above didn't worked.

perfectly works :
1
2
3
4
5
6
7
8
9
    int i = 0;
    while( fileIn >> book[ i ].bookId &&
           fileIn.ignore() &&
           fileIn.getline( book[ i ].title, MAX_CHAR ) &&
           fileIn.getline( book[ i ].author, MAX_CHAR ) &&
           ++i != MAX_BOOKS )
    {

    }
Last edited on
Topic archived. No new replies allowed.