I don't understand this behavior

I'm not sure why but whenever I have a two loops the size() function always returns 0

example below

line 18 always prints out the correct size.

line 24 always prints out zero.

I could switch to using an array or another container to make the program work correctly, I just don't understand why this code here does not work. (I tried .length() also and it's the same behavior)

Any ideas on what is going wrong?

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
#include <iostream>
#include <fstream>
#include <string>
#define Custom_Music_List "custom_music.txt"

int main (){

    std::ifstream Music_List;
    std::string buffer;

    Music_List.open(Custom_Music_List);

    for (int i = 0; i < 13; i++){
        buffer.clear();
        getline(Music_List, buffer);
    }

    std::cout << "\nBuffer size: " << buffer.size(); //Buffer size is correct

    do{
    buffer.clear();
    getline(Music_List, buffer);

    std::cout << "\nBuffer size: " << buffer.size(); //buffer size is always zero
    }while(!Music_List.eof());

    return 0;
}
Last edited on
What are the contents of "custom_music.txt"?
If there are 13 lines or less in that file, then line 24 prints 0 because you call buffer.clear(); on line 21 and then try to read in another line from the file on line 22, which fails since you've already reached the end of the file.

Or something like that.
You were correct, my count was off by one.

feel kind of stupid now >_<

I was trying to ignore the first few notes i put in the music list that I put at the start of the file. Then the program would read the the song locations I wanted to play. I had only added one song to the file though and since my count was off by one it was ignoring that one extra line and since there were no lines to read, it would be zero.

Thanks for the help :)
Last edited on
Topic archived. No new replies allowed.