Monday, May 06, 2024

"Learn C++ by Example" by Frances Buontempo

Currently taking part in a study group for the abovementioned book.

I was curious to see if I could write a simple filter. Using cppreference.com for information on the C++ standard libraries, I came up with this, saved into the file irb-filter.cpp:-

/*
  The most basic filter ever, copies cin to cout.

  Ian Bruntlett 5th May 2024

  To check for memory errors, do this:
  $ valgrind --tool=memcheck ./irb-filter <rose.txt

  To see cache performance, do this:
  $ valgrind --tool=cachegrind ./irb-filter <rose.txt

  See valgrind.org for more info on valgrind
 
*/

#include <iostream>
#include <string>

int main()
{
  std::string line;
 
  //std::cout << "line.capacity() = " << line.capacity() << '\n';
  //line.reserve(200); // assume lines typically 200 characters or less

  while ( std::getline(std::cin,line) )
    std::cout << line << '\n';
    //std::cout << line.capacity() << " length " << line.length() << ' ' << line << '\n';
}

I've left in some comments in case the reader want to delve a bit deeper. I've also left in some commented bits of code I used to check my understanding of what is happening when the code is being run.

I compiled the code with my makefile, which in turn ran this command:

g++ -g -Wall -Wshadow -Wconversion -std=c++23  -Wl,-Map=irb-filter.map  irb-filter.cpp   -o irb-filter

Here are the contents of rose.txt:

 The Sick Rose
By William Blake
O Rose thou art sick.
The invisible worm,
That flies in the night
In the howling storm:

Has found out thy bed
Of crimson joy:
And his dark secret love
Does thy life destroy.

No comments: