Created
May 21, 2018 04:57
-
-
Save yumetodo/de9eb8b1666c1c227b4a5682142fd794 to your computer and use it in GitHub Desktop.
pgm(P2) image reformatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
#include <string> | |
int proc_main(std::istream& is, std::ostream& os) | |
{ | |
std::string pn; | |
if(!std::getline(is, pn)) return 1; | |
if("P2" != pn) return 2; | |
std::string tmp; | |
if(!std::getline(is, tmp)) return 3; | |
if(tmp.empty() || '#' != tmp[0]) return 4; | |
std::string size; | |
if(!std::getline(is, size)) return 5; | |
const auto width = std::size_t(std::stoul(size.substr(0, size.find_first_of(' ')))); | |
const auto height = std::size_t(std::stoul(size.substr(size.find_first_not_of(' ', size.find_first_of(' '))))); | |
for( | |
std::size_t i = 0, j = 0; | |
[&is](std::string& buf) -> std::istream& { | |
while(auto& re = std::getline(is, buf)) if(buf.empty() || '#' != buf[0]) return re; | |
return is; | |
}(tmp); | |
){ | |
for( | |
std::size_t pos = 0, pre_pos = 0; | |
std::string::npos != pre_pos; | |
pre_pos = (std::string::npos == pos) ? pos : tmp.find_first_not_of(' ', pos) | |
){ | |
pos = tmp.find_first_of(' ', pre_pos); | |
if(0 != j) os << ' '; | |
os << tmp.substr(pre_pos, pos - pre_pos); | |
if(++j == width){ | |
if(++i == height){ | |
os << std::flush; | |
return 0; | |
} | |
j = 0; | |
os << std::endl; | |
} | |
} | |
} | |
os << std::flush; | |
return 0; | |
} | |
constexpr auto input = R"(P2 | |
# Created by IrfanView | |
7 4 | |
255 172 9 | |
31 7 9 14 | |
221 187 1 | |
0 92 33 7 | |
182 21 37 | |
22 3 5 71 | |
92 23 143 | |
22 5 7 21)"; | |
int main() | |
{ | |
std::istringstream iss(input); | |
return proc_main(iss, std::cout); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://wandbox.org/permlink/SzJ55T77lushcySA
https://teratail.com/questions/127103