DEV Community

Cover image for Use this Modern scanf for C++
Marcos Oliveira
Marcos Oliveira

Posted on

4

Use this Modern scanf for C++

scnlib is a modern C++ library to replace scanf and std::istream. This library tries to bring us even closer to the complete replacement of iostream
and stdio in C.

It's faster than iostream and typed, unlike scanf. Think of {fmt} or std::format in C++20, but in another direction.

This library is the reference implementation of the ISO C++ standards proposal P1729 "Text Parsing".


Installation

To compile, simply clone with git and use CMake and install:

git clone https://github.com/eliaskosunen/scnlib
cd scnlib
cmake -B build .
cmake --build build
sudo cmake --install build
Enter fullscreen mode Exit fullscreen mode

After that, you can exit the repository and remove it: cd .. && rm -rf scnlib.


Basic example

In this example, in addition to scnlib, there is also the use of println from C++23, we will read 2 numbers via prompt and their sum will automatically be displayed:

main.cpp

#include <scn/scan.h>
#include <print>

constexpr auto sum = [](int x, int y){
  return x + y;
};

int main(){
  if(auto result =
      scn::prompt<int, int>("Enter 2 numbers to add? ", "{} {}")){
      auto [a, b] = result->values(); std::println("The sum of {} plus {} is: {}", a, b, sum(a, b));
  }else{
      std::println(stderr, "Error: {}", result.error().msg());
  }
}
Enter fullscreen mode Exit fullscreen mode

To compile, use the flag: -lscn:

g++ main.cpp -lscn
Enter fullscreen mode Exit fullscreen mode

Then, run the binary and test, example:

./a.out
Enter 2 numbers to add? 3 6
The sum of 3 plus 6 is: 9
Enter fullscreen mode Exit fullscreen mode

For more information, access the official repository and the address: https://scnlib.dev/.

Heroku

Amplify your impact where it matters most — building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

DevCycle image

Ship Faster, Stay Flexible.

DevCycle is the first feature flag platform with OpenFeature built-in to every open source SDK, designed to help developers ship faster while avoiding vendor-lock in.

Start shipping