getline With ifstream Object Returning Erroneous Values

After being bored at school and making a program that utilized the Beep function to annoy other students, I decided to try making it play the Mario theme. In order to do so I've created a very simple (and very unoptimized) parser to load a file of notes grouped by 3s, the information for each note being on a different line. The code for loading the file and sorting the notes is:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
    std::vector<CNote>* pNoteSequence = new std::vector<CNote>;

    std::istringstream strm;
    short NoteLength, Octave;

    std::ifstream SeqFile (FileName);
    if (!SeqFile.is_open ())
        throw std::exception ("Unable to find file.");

    std::string InputString;
    CNote Note;

    while (!SeqFile.eof ())
    {
        //    Get the note (A, A#, B, C, C#, etc.)
        getline (SeqFile, InputString);
        Note.Note = InputString;

        //    Get the note duration
        getline (SeqFile, InputString);
        strm.str (InputString);
        strm >> NoteLength;

        switch (NoteLength)
        {
        case (1):
            Note.Length = Whole;
            break;
        case (2):
            Note.Length = Half;
            break;
        case (4):
            Note.Length = Quarter;
            break;
        case (8):
            Note.Length = Eighth;
            break;
        case (16):
            Note.Length = Sixteenth;
            break;
        case (32):
            Note.Length = Thirtysecond;
            break;
        default:
            SeqFile.close ();
            delete pNoteSequence;
            throw std::exception ("Error: Invalid note duration.");
            break;
        }

        //    Get the octave
        getline (SeqFile, InputString);
        strm.str (InputString);
        strm >> Octave;
        Note.Octave = Octave;
        pNoteSequence->push_back (Note);
    }

    SeqFile.close ();
    return pNoteSequence;


Using sample file:

A // Note
2 // Length (Half note)
4 // Octave


gives -13108 for the octave, but every other value is obtained just fine. Anyone have any idea what's going on?
You need a strm.clear(); call before strm >> Octave;
I thought that using strm.str () would completely change the internal string?

But your strm.clear() solution has worked, so thanks for that.
Last edited on
Topic archived. No new replies allowed.