Skip to content

Commit

Permalink
Add file function test
Browse files Browse the repository at this point in the history
  • Loading branch information
jorg-vr committed Jul 29, 2024
1 parent d367fe5 commit 2ec43b9
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions tests/exercises/echo-function-file/solution/correct.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <cctype>

std::string trim(const std::string& str) {
std::string trimmed = str;
trimmed.erase(trimmed.begin(), std::find_if(trimmed.begin(), trimmed.end(), [](int ch) {
return !std::isspace(ch);
}));
trimmed.erase(std::find_if(trimmed.rbegin(), trimmed.rend(), [](int ch) {
return !std::isspace(ch);
}).base(), trimmed.end());
return trimmed;
}

std::string echo_file(const std::string& filename) {
std::ifstream file(filename);
if (!file) {
return "Error: Failed to open file.";
}

std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return trim(content);
}

0 comments on commit 2ec43b9

Please sign in to comment.