简体   繁体   中英

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
}

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM