DEV Community

Cover image for Utilize esse scanf Moderno para C++
Marcos Oliveira
Marcos Oliveira

Posted on

2

Utilize esse scanf Moderno para C++

scnlib é uma biblioteca C++ moderna para substituir scanf e std::istream. Esta biblioteca tenta nos aproximar ainda mais da substituição completa de iostream
e stdio em C.

É mais rápida que iostream e tipada, ao contrário de scanf. Pense em {fmt} ou em std::format em C++20, mas em outra direção.

Esta biblioteca é a implementação de referência da proposta de padrões ISO C++ P1729 "Análise de Texto".


Instalação

Para compilar basta clonar com git e usar o CMake e instalar:

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

Após isso, já pode sair do repositório e removê-lo: cd .. && rm -rf scnlib.


Exemplo básico

Nesse exemplo, além da scnlib também há o uso o println do C++23, vamos ler 2 números via prompt e automaticamente será exibida a soma deles:

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>("Informe 2 números para somar? ", "{} {}")) {
    auto [a, b] = result->values();
    std::println("A soma de {} mais {} é: {}", a, b, sum(a, b));
  }else{
    std::println(stderr, "Error: {}", result.error().msg());
  }
}
Enter fullscreen mode Exit fullscreen mode

Para compilar use a flag: -lscn:

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

E então, rode o binário e teste, exemplo:

./a.out
Informe 2 números para somar? 3 6
A soma de 3 mais 6 é: 9
Enter fullscreen mode Exit fullscreen mode

Para mais informações acesse o repositório oficial e o endereço: https://scnlib.dev/.

Embedded BI Dashboards are 💩 Building them yourself is 💩

Embedded BI Dashboards are 💩 Building them yourself is 💩

Use our developer toolkit to build fast-loading, native-feeling dashboards for your customers (without the sh*t).

Get early access

Top comments (0)

Warp.dev image

Warp is the #1 coding agent.

Warp outperforms every other coding agent on the market, and gives you full control over which model you use. Get started now for free, or upgrade and unlock 2.5x AI credits on Warp's paid plans.

Download Warp

👋 Kindness is contagious

Explore this insightful piece, celebrated by the caring DEV Community. Programmers from all walks of life are invited to contribute and expand our shared wisdom.

A simple "thank you" can make someone’s day—leave your kudos in the comments below!

On DEV, spreading knowledge paves the way and fortifies our camaraderie. Found this helpful? A brief note of appreciation to the author truly matters.

Let’s Go!