The key to doing what you want in C++ is to take advantage of the formatted input operations. You want to ignore whitespace; the formatted input methods do exactly that.
Here is one way, using the canonical C++ input loop:
#include <fstream>
#include <iostream>
int main () {
std::ifstream inFile("input.txt");
char c;
std::string result;
while(inFile >> c)
result.push_back(c);
std::cout << result;
}
I prefer standard algorithms to hand-crafted loops. Here is one way to do it in C++, using std::copy
. Note that this way and the first way are nearly identical.
#include <vector>
#include <fstream>
#include <iostream>
#include <iterator>
#include <algorithm>
int main () {
std::ifstream inFile("input.txt");
std::string result;
std::copy(std::istream_iterator<char>(inFile),
std::istream_iterator<char>(),
std::back_inserter(result));
std::cout << result;
}
Another way, this time with std::accumulate
. std::accumulate
uses operator+
instead of push_back
, so we can read the file in a string
at a time.
#include <vector>
#include <fstream>
#include <numeric>
#include <iostream>
#include <iterator>
#include <algorithm>
int main () {
std::ifstream inFile("input.txt");
std::string result =
std::accumulate(
std::istream_iterator<std::string>(inFile),
std::istream_iterator<std::string>(),
std::string());
std::cout << result;
}