strange behavior at switch directive

I'm wondering why at the below code within the switch directive the 'default' branch will executed at line 26. That should never happen if the input file supplies correct formatted data.

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
61
62
#include <iostream>
#include <fstream>
#include <vector>
#include <exception>

enum class Note { A, B, C, D, E, F, G };
enum class String { E, A, D, G, B };
struct Pos
{
    Note m_note;
    int m_fret;
    String m_string;
};

std::istream & operator>>( std::istream & is, String & string)
{
    std::string tmp;
    is >> tmp;
    switch(tmp[0])
    {
        case 'E': string = String::E; break;
        case 'A': string = String::A; break;
        case 'D': string = String::D; break;
        case 'G': string = String::G; break;
        case 'B': string = String::B; break;
        default:
            //std::cout << (int)tmp[0];
            throw std::runtime_error("Wrong_string:"+tmp+"!");
    }
    return is;
}
std::istream & operator>>( std::istream & is, Note & note)
{
    std::string tmp;
    is >> tmp;
    switch(tmp[0])
    {
        case 'A': note = Note::A; break;
        case 'B': note = Note::B; break;
        case 'C': note = Note::C; break;
        case 'D': note = Note::D; break;
        case 'E': note = Note::E; break;
        case 'F': note = Note::F; break;
        case 'G': note = Note::G; break;
        default:
            throw std::runtime_error("Wrong_note:"+tmp+"!");
    }
    return is; 
}
std::istream & operator>>( std::istream & is, Pos & pos)
{
    is >> pos.m_string >> pos.m_fret >> pos.m_note;
    return is;
}

int main()
{
    std::ifstream ifs("notes_on_frets.txt");
    Pos pos;
    std::vector<Pos> pos_v;
    while( ifs >> pos) pos_v.push_back(pos);
}


A short sample of notes_on_frets.txt file:
E 0 E
E 1 F
E 3 G
E 5 A
E 7 B
E 8 C
Any idea what's going wrong?
Last edited on
On lines 18, 35, and for >> pos.m_fret on line 52 you're not checking whether anything was read correctly. What happens when you reach the end of input?
What fix would you suggest?

I've tried changing line 61 to:
1
2
3
4
5
6
    while( ifs.good() )
    {
        ifs >> pos;
         pos_v.push_back(pos);
     }
}

for fetching the eof, but this doesn't work :(

*edit:
Now I test the stream before the swiches will executed and letting the streams immediately return if input couldn't read and it works fine.
Last edited on
Remember to change line 61 back. What you had was correct, the while(ifs.good()) replacement is wrong.
Topic archived. No new replies allowed.