Code πŸ‘¨β€πŸ’», file reading in C++ πŸ—‚οΈ, vimrc πŸš€

By Prajwal Haniya

Techletter #84 | August 3, 2024

Writing better code

A program is written for two audiences. Naturally, we write code for computers to execute. However, we spend long hours reading and modifying the code. Thus, programmers are another audience for programs. So, writing code is also a form of human-to-human communication. In fact, it makes sense to consider the human readers of our code our primary audience: if they (we) don’t find the code reasonably easy to understand, the code is unlikely to ever become correct. So, please don’t forget: code is for reading β€” do all you can to make it readable.


How to Read a file in C++?

Below is the code for reading a file in C++.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    string myText;

    // Create an input file stream object
    ifstream MyReadFile("filename.txt");

    // Check if the file opened successfully
    if (!MyReadFile) {
        cout << "Unable to open file";
        return 1; // Exit if file not opened
    }

    // Use a while loop with getline to read the file line by line
    while (getline(MyReadFile, myText)) {
        // Output the text from the file
        cout << myText << endl;
    }

    // Close the file
    MyReadFile.close();

    return 0;
}

Configuring vim

Below is the .vimrc file

Using vim is not straight forward. It takes a lot of configuration before you can make it usable. I am trying to use vim because the speed it offers is just mind blowing. And while coding, I would like my editor to be much more quick.

I have added the below configuration which is working for me. You can follow this video for complete information.

  0 syntax on
  1 filetype plugin indent on
  2 set ts=2 sts=2 sw=2 et ai si
  3 set rnu
  4 call plug#begin()
  5
  6 Plug 'neoclide/coc.nvim'
  7 Plug 'jiangmiao/auto-pairs'
  8 Plug 'gruvbox-community/gruvbox'
  9 Plug 'vim-airline/vim-airline'
 10 Plug 'vim-airline/vim-airline-themes'
 11 Plug 'preservim/nerdtree'
 12
 13 call plug#end()
 14
 15 " use <tab> to trigger completion and navigate to the next complete item"
 16 function! CheckBackspace() abort
 17   let col = col('.') - 1
 18   return !col || getline('.')[col - 1]  =~# '\s'
 19 endfunction
 20
 21 inoremap <silent><expr> <Tab>
 22       \ coc#pum#visible() ? coc#pum#next(1) :
 23       \ CheckBackspace() ? "\<Tab>" :
 24       \ coc#refresh()
 25
 26 colo gruvbox
 27
 28 inoremap <c-b> <Esc>:NERDTreeToggle<cr>
 29 nnoremap <c-b> <Esc>:NERDTreeToggle<cr>
 30
 31 set clipboard=unnamedplus