Search code examples
c++ppm

Read PPM files RGB values C++


I'm trying read from a PPM file. I want to read the first, second and third number from each row, in this file, but I don´t know how to read the lines.

This is what I have so far:

for (int y = 4; y <= HEIGHT; y++) { // i think it has to start on row 4 
    for (int x = 1; x <= WIDTH; x++) { // and x from 1
         int i = 4;

         int r = CurrentR(i);
         int g = CurrentG(i);
         int b = CurrentB(i);
         i++;
    }   
}

int CurrentR(int I) {
    return // the first number in row xy
}
int CurrentG(int I) {
    return // the second number in row xy
}
int CurrentB(int I) {
    return // the third number in row xy
}

Solution

  • This is how I would suggest you to do it:

    struct RGB {
        int R,B,G;
    }
    std::ifstream& operator>>(std::ifstream &in,RGB& rgb){
        in >> rgb.R;
        in >> rgb.G;
        in >> rgb.B;
        return in;
    }
    std::ostream& operator<<(std::ostream &out,RGB& rgb){
        out << rgb.R << " ";
        out << rgb.G << " ";
        out << rgb.B << std::endl;
        return out;
    }
    
    
    int main(){
        std::string filename = "test.txt";
        std::ifstream file(filename.c_str());
        if(file.is_open()) {
            std::string line;
            for (int i=0;i<4;i++) { std::getline(file,line); }
            RGB rgb;
            for (int i=0;i<LINES_TO_READ;i++) {
                file >> rgb;
                std::cout << rgb;
            }
        }
    }